Can someone explain how yield is working in the code below?
def countdown(n):
print("Counting down from", n)
while n >= 0:
newvalue = (yield n)
if newvalue is not None:
n = newvalue
else:
n -= 1
c = countdown(5)
for n in c:
print n
if n == 4:
c.send(2)
output
('Counting down from', 5)
5
4
1
0
I expected it to be
('Counting down from', 5)
5
4
2
1
0
Where is "2" getting lost?
Tracing these two events (receive and produce) simultaneously is getting a bit trickier. This is not a duplicate of python generator "send" function purpose? because that question is mostly focused on understanding the need for coroutines and how they defer from generators. My question is very specific to a problem with using coroutines and generators together.