Why the second next
doesn't return "bye"
?
def salute():
yield "hello"
yield "bye"
def greet_me():
print(next(salute()))
print(next(salute()))
greet_me()
Output :
hello
hello
Because you're creating a new generator each time you call salute()
. Create the generator once and then call next
on it to get both yields to yield their value:
def greet_me():
gen = salute() # create the generator
print(next(gen)) # start it, goes to the first yield
print(next(gen)) # resume it, goes to second yield
Calling greet_me
now prints the expected results.