fork download
  1. def regular_function():
  2. return 2
  3.  
  4. print regular_function()
  5.  
  6. try:
  7. for i in regular_function():
  8. print i
  9. except:
  10. print "Oops, you can't iterate over a regular function!"
  11.  
  12. def generator():
  13. n = 0
  14. while True:
  15. yield n
  16. n += 1
  17.  
  18. print generator()
  19. print "Huh, that looks funny..."
  20.  
  21. for i in generator():
  22. print i
  23. if i >= 5:
  24. print "We should stop this, since it's an infinite loop..."
  25. break
  26.  
  27. print "Much better..."
  28.  
  29. import itertools
  30.  
  31. print [i for i in itertools.takewhile(lambda x:x<5, generator())]
  32. print "Neat, we can use itertools stuff with generators!"
Success #stdin #stdout 0.02s 9016KB
stdin
Standard input is empty
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!