Python: two "yield"s in one function -


we find interesting issue on yield of python. wrote simple program:

def f():     in range(5, 9):         j in range(21, 29):             x = yield             y = (yield j) * 100             x += y             print '>>>', x  gen = f() next(gen) a1 = gen.send(66) a2 = gen.send(77) print a1 print a2 

the result amazing:

>>> 7766 21 5 

i=5, j=21 => yield => a1=21 => send(66) => x = 66

i=5, j=21 => yield j => a2=5 => send(77) => y = 7700

print 7766

print 21

print 5

i.e. after yield i, a1 gets value of j; after yield j, a2 gets value of i.

does know why yield this? why not a1=5, a2=21?

next(gen) takes first element generator (i):

next(gen) # 5 

then gen.send(66) equal j (which 21). since second loop still working, subsequent gen.send(77) equal i (which still 5).

essentially, problem consume 3 values, instead of 2.

use gen.send(none) or next(gen) start generator:

a1 = gen.send(none) # or a1 = next(gen) a2 = gen.send(77) print(a1, a2) # prints 5 21 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -