Unlike a normal function, it seems to remember the value returned last time. When called, it returns the following value:
generator.py
def counter(num=10):
for _ in range(num):
yield 'run'
def greeting():
yield 'good morning'
yield 'good afternoon'
yield 'good night'
for g in greeting():
print(g)
g=greeting()
print(next(g)) #good morning
print(next(g)) #good afternoon
c=counter()
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
#print(next(c))I get an error
output:
good morning
good afternoon
good night
good morning
good afternoon
run
run
run
run
run
run
run
run
run
run
Recommended Posts