grocery_stocker wrote:
...
while True:
...    i = gen.next()
...    print i
...
0
1
4
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
StopIteration

If you had written

for item in gen: print(i)

then StopIteration from gen would be caught.

One expansion of a for loop is (in the above case)

it = iter(gen) # not needed here, but is for general iterables
try:
  while True:
    i = it.next()
    print(i) # or whatever the loop body is
except StopIteration:
  pass

In other words, 'for i in iterable' expands to several lines of boilerplate code. It is very useful syntactic sugar.

You left out the try..except part.

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to