Generators (yield). Send() method. | Sololearn: Learn to code for FREE!
+ 9

Generators (yield). Send() method.

Can somebody please explain me how does send() method work in generators? https://code.sololearn.com/c28YFxTnaak2/?ref=app

16th Feb 2020, 12:06 PM
Mikhail
Mikhail - avatar
5 ответов
+ 6
Send makes the next yield Docu says send(None) is equal to yield
16th Feb 2020, 3:30 PM
Oma Falk
Oma Falk - avatar
+ 6
I commented in code. that is indeed very interesting
16th Feb 2020, 6:36 PM
Oma Falk
Oma Falk - avatar
+ 5
After reading the docs and thinking a while, I come to the following result: a.send(100) does not send x but the yield expression yield x. Python must do so, otherwise it had problems handling send() for a generator gen(x,y): while True: yield(3x +4y) What would you send in this case if send has exactly 1 argument. As a model u can regard yield x as a variable that is created with first yield and can be manipulated with send()
16th Feb 2020, 1:49 PM
Oma Falk
Oma Falk - avatar
+ 5
But if so, why in my second example (gen1) where generator uses double “yield” statement, b.send(100) prints out 100?
16th Feb 2020, 2:27 PM
Mikhail
Mikhail - avatar
+ 5
So, send() does the same as next()? P.S. If you run my code now, you will see a very interesting thing in the second example with double “yield”! It looks like these two “yields” work one after another: with first “next()” it prints out the first element of generator (so I guess the inner “yield x” does this), but with second “next()” it prints out “None” (as if outer “yield” is doing this). And if I write “send(value)” instead of the second “next()”, it prints out the “value” of “send”!
16th Feb 2020, 6:32 PM
Mikhail
Mikhail - avatar