Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #97925
| From | Nobody <nobody@nowhere.invalid> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Resetting the Range start in the middle of a loop |
| Date | 2015-10-24 03:13 +0100 |
| Organization | A noiseless patient Spider |
| Message-ID | <pan.2015.10.24.02.13.54.891000@nowhere.invalid> (permalink) |
| References | <ea58da60-3fb1-46e1-91db-ed48beebfd5c@googlegroups.com> |
On Fri, 23 Oct 2015 08:42:53 -0700, bigred04bd3 wrote:
> I am wanting to reset a Range start while a loop is running. here is what
> I have:
>
> s = 1
> for i in range(s, 1000):
> # do stuff
> for r in range(i, 1000):
> # do stuff
> s = s + 100 #example
> break
>
>
> I've also tried to update the i as well, but it just continues on to the
> next number as if it was never updated.
You either need a while loop or a custom iterator. E.g.:
class Iterator(object):
def __init__(self, start, end):
self.cur = start
self.end = end
def set(self, cur):
self.cur = cur
def __iter__(self):
return self
def next(self):
if self.cur >= self.end:
raise StopIteration
i = self.cur
self.cur += 1
return i
So then you can do e.g.:
it = Iterator(s, 1000)
for i in it:
# do stuff
for r in range(i, 1000):
# do stuff
s = s + 100 #example
it.set(s)
break
Unless you need to do this sort of thing a lot, use a while loop.
A "for" loop is used when the set of values is known in advance.
C's "for" loops (since copied by other C-like languages) are "while" loops
in disguise. Python's "for" loops are actually "for" loops.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Resetting the Range start in the middle of a loop bigred04bd3@gmail.com - 2015-10-23 08:42 -0700 Re: Resetting the Range start in the middle of a loop John Gordon <gordon@panix.com> - 2015-10-23 17:15 +0000 Re: Resetting the Range start in the middle of a loop Peter Pearson <pkpearson@nowhere.invalid> - 2015-10-23 17:23 +0000 Re: Resetting the Range start in the middle of a loop Steven D'Aprano <steve@pearwood.info> - 2015-10-24 11:05 +1100 Re: Resetting the Range start in the middle of a loop Nobody <nobody@nowhere.invalid> - 2015-10-24 03:13 +0100 Re: Resetting the Range start in the middle of a loop bigred04bd3@gmail.com - 2015-10-23 19:31 -0700
csiph-web