generator_send.py 504 B

12345678910111213141516171819202122232425262728293031323334353637
  1. def f():
  2. n = 0
  3. while True:
  4. n = yield n + 1
  5. print(n)
  6. g = f()
  7. try:
  8. g.send(1)
  9. except TypeError:
  10. print("caught")
  11. print(g.send(None))
  12. print(g.send(100))
  13. print(g.send(200))
  14. def f2():
  15. print("entering")
  16. for i in range(3):
  17. print(i)
  18. yield
  19. print("returning 1")
  20. print("returning 2")
  21. g = f2()
  22. g.send(None)
  23. g.send(1)
  24. g.send(1)
  25. try:
  26. g.send(1)
  27. except StopIteration:
  28. print("caught")
  29. try:
  30. g.send(1)
  31. except StopIteration:
  32. print("caught")