0

What is the difference between return and yield

19th Jun 2019, 10:03 PM
Micheal Shenouda Gad
Micheal Shenouda Gad - avatar
8 ответов
+ 7
River Your analogy reminds me of the Little Man Computer (LMC) for some reason. 😂👌 - Not that LMC is related to yield vs return. 😉 Micheal Shenouda Gad While the analogy is helpful for understanding this from 50,000 feet, the more technical explanation requires an understanding of python iterables and generators, which might sound more complex than they really are. Here are some references to understand these better: https://realpython.com/introduction-to-python-generators/ https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/ In the meantime, I'll expand on River's explanation by pointing out that yield is essentially a pause button for a function. The 1st time a function is called, the code runs until it hits a yield statement. The yield statement saves the local state and returns a value. The next time the function is called, the code resumes where it left off and runs until it hits the next yield or reaches the end of the function. I hope this helps as well.
20th Jun 2019, 5:51 AM
David Carroll
David Carroll - avatar
+ 7
I'm not great at Python, but here is a basic answer. Return is where it exits from a function with a value, but the local values within is destroyed. Yield is sort of exiting from a function but it remembers the state you had when you exited. If you were to do a 'next' from your 'main' you would be starting from the point you yielded from. Hope this helps!
19th Jun 2019, 10:30 PM
River
River - avatar
+ 7
Best I can. Imagine a function to be a room. Now imagine you entered that room and incremented a counter which had been initialised to 0. The value of this counter is 1. Now you return to the spot you were before you entered the room(your main). If you were asked to back in the room, the value of the counter would depend on how you had exited. If you had 'returned' from the room, the counter value would be 0. If you had yielded, the value would be 1. Hope this helps!
19th Jun 2019, 11:25 PM
River
River - avatar
+ 1
Thanks But can you tell me more because I didn't understand
19th Jun 2019, 11:12 PM
Micheal Shenouda Gad
Micheal Shenouda Gad - avatar
+ 1
Thanks River
20th Jun 2019, 12:06 AM
Micheal Shenouda Gad
Micheal Shenouda Gad - avatar
+ 1
Simply, yes.
20th Jun 2019, 5:06 AM
River
River - avatar
+ 1
20th Jun 2019, 11:23 AM
Micheal Shenouda Gad
Micheal Shenouda Gad - avatar
0
River I will discuss to you what I had understand. "yield" can store informations more than once while "return store information only once upon a time.. Is that true??
20th Jun 2019, 12:19 AM
Micheal Shenouda Gad
Micheal Shenouda Gad - avatar