Python generator

generator
# A simple generator function
def my_gen():
   n = 1
   print('This is printed first')
   # Generator function contains yield statements
   yield n
 
   n += 1
   print('This is printed second')
   yield n
 
   n += 1
   print('This is printed at last')
   yield n
 
g = my_gen()
next(g)
--------------------
This is printed first
-------------------
next(g)
--------------------
This is printed second
---------------------
 
for i in my_gen():
   print(i)
----------------------
This is printed first
1
This is printed second
2
This is printed at last
3

댓글