Anyone to explain this Python yield function below? This was a SoloLearn challenge. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Anyone to explain this Python yield function below? This was a SoloLearn challenge.

def count(n = 0): while True: yield (yield n) n += 1 a = count() next(a) print(a.send(5), end='') print(a.send('a')) # 51 My questions: (1) What does the double yield do in line 3? (2) Why does function count executes only one time if while remains True? (3) Why does “next(a)” stop in line 3 without continuing to line 4? (4) How can does print(a.send(5), end='') return with 5 without going into function count?

23rd Dec 2019, 7:00 AM
Prof. Dr. Zoltán Vass
2 Answers
+ 2
I think I can explain the code line by line : a = count() Nothing happen, only creates the generator next(a) It yields n (0) without yielding a second time : only execute 'yield n', not the second yield. print(a.send(5)) 5 becomes the 'output' of the previous 'yield n'. The second yield keyword will now yield the output : 5 print(a.send('a')) It yields first n (now 1) (it prints 1) and put 'a' as the result of 'yield n'. The second yield is not executed yet : it will return 'a' if you do : print(next(a)) What you need to understand : yield exits the function directly, and save the function state. In your code : yield (yield n) If you call it a first time, it will execute 'yield n'. If you call it a second time, it will execute 'yield + output of previous yield'. A third time : it will execute 'yield n' again, and so on.
23rd Dec 2019, 8:40 AM
Théophile
Théophile - avatar
+ 1
https://code.sololearn.com/cd5i0vvY1w6L/?ref=app I made this code for your question. Hope that you'll understand better. 1) the double yield works because the yield keyword return either nothing or what you send by function send 2) the yield keyword is blocking : it execute once the instruction until the yield keyword then wait for a second next : that means that you're still inside the loop at the end. 4) in fact, it goes inside the function. The send function send an object as the output of a yield keyword. In the example, it yields the number sent (5) because it is the result of the previous yiel (yield n). That's crazy, I know.
23rd Dec 2019, 8:22 AM
Théophile
Théophile - avatar