def regular_function( ) :
return 2
print regular_function( )
try :
for i in regular_function( ) :
print i
except :
print "Oops, you can't iterate over a regular function!"
def generator( ) :
n = 0
while True :
yield n
n += 1
print generator( )
print "Huh, that looks funny..."
for i in generator( ) :
print i
if i >= 5 :
print "We should stop this, since it's an infinite loop..."
break
print "Much better..."
import itertools
print [ i for i in itertools .takewhile ( lambda x:x< 5 , generator( ) ) ]
print "Neat, we can use itertools stuff with generators!"
ZGVmIHJlZ3VsYXJfZnVuY3Rpb24oKToKCXJldHVybiAyCgkKcHJpbnQgcmVndWxhcl9mdW5jdGlvbigpCgp0cnk6Cglmb3IgaSBpbiByZWd1bGFyX2Z1bmN0aW9uKCk6CgkJcHJpbnQgaQpleGNlcHQ6CglwcmludCAiT29wcywgeW91IGNhbid0IGl0ZXJhdGUgb3ZlciBhIHJlZ3VsYXIgZnVuY3Rpb24hIgoJCmRlZiBnZW5lcmF0b3IoKToKCW4gPSAwCgl3aGlsZSBUcnVlOgoJCXlpZWxkIG4KCQluICs9IDEKCnByaW50IGdlbmVyYXRvcigpCnByaW50ICJIdWgsIHRoYXQgbG9va3MgZnVubnkuLi4iCgpmb3IgaSBpbiBnZW5lcmF0b3IoKToKCXByaW50IGkKCWlmIGkgPj0gNToKCQlwcmludCAiV2Ugc2hvdWxkIHN0b3AgdGhpcywgc2luY2UgaXQncyBhbiBpbmZpbml0ZSBsb29wLi4uIgoJCWJyZWFrCgkKcHJpbnQgIk11Y2ggYmV0dGVyLi4uIgoKaW1wb3J0IGl0ZXJ0b29scwoKcHJpbnQgW2kgZm9yIGkgaW4gaXRlcnRvb2xzLnRha2V3aGlsZShsYW1iZGEgeDp4PDUsIGdlbmVyYXRvcigpKV0KcHJpbnQgIk5lYXQsIHdlIGNhbiB1c2UgaXRlcnRvb2xzIHN0dWZmIHdpdGggZ2VuZXJhdG9ycyEi
stdout
2
Oops, you can't iterate over a regular function!
<generator object generator at 0xb72dbbbc>
Huh, that looks funny...
0
1
2
3
4
5
We should stop this, since it's an infinite loop...
Much better...
[0, 1, 2, 3, 4]
Neat, we can use itertools stuff with generators!