[PYTHON] generator

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

generator
Generator
Generator memo.
Natural number generator
Patterned password generator
Hash password generator
[Python] Generator function
Generator function in JavaScript
Lektor static site generator
Generator comprehension notation Tuple comprehension notation
Password generator creation notes
Zundokokiyoshi (generator) in Python
NetworkX graph generator list