The else
block in a for
/else
clause gets executed if the iteration finishes but is not interrupted by break
, so I read.
Is there a language construct which would let me write something which executes only if the for
loop did not begin iteration? If I was using a tuple
or list
, I would do something like this:
if seq:
for x in seq:
# something
else:
# something else
But when I use a generator, I don't get the behavior I want:
>>> g = (x for x in range(2))
>>> for x in g:
... print x
... else:
... print "done"
...
0
1
done # I don't want "done" here
>>> g = (x for x in range(2) if x > 1)
>>> if g:
... for x in g:
... print x
... else:
... print "done"
...
>>> # I was expecting "done" here
How can I do this without exhausting creating a tuple
or a list
from the generator, while also using a for
loop? I could use next()
in a while
loop and try to catch StopIteration
, but I'd like to see if there's a nice way to do it with for
.
For Loops using range() start states the integer value at which the sequence begins, if this is not included then start begins at 0.
There are two variations of the while loop – while and do-While. The difference between the two is that do-while runs at least once. A while loop might not even execute once if the condition is not met.
With a do while loop the condition is not evaluated until the end of the loop. Because of that a do while loop will always execute at least once. A for-loop always makes sure the condition is true before running the program. Was this answer helpful?
n = -1
for n, i in enumerate(it):
do_stuff()
if n < 0:
print 'Done'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With