Why can't we use print instead of yield? The output is same. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why can't we use print instead of yield? The output is same.

2nd Jan 2019, 4:22 AM
Jobin Jose
Jobin Jose - avatar
2 Answers
+ 10
Could you please post the code you're talking about? That would make it easier to answer your question. 'Yield' is a generator's equivalent to 'return' in a normal function. It can't be replaced with 'print' because those are totally different things. A generator generates data and waits until the information is 'called'. In contrast to a function, a generator will only generate one piece of data at a time, wait until the generated data is called, generate the next piece of data on call etc. Regular functions generate and return everything at once. Again, please post the code if you want a better explanation.
2nd Jan 2019, 5:43 AM
Anna
Anna - avatar
+ 2
If you print the result of your function directly in the function, after the function ends, the value will be lost. If that's okay for you, you can totally use print. But if you want to store what you calculated for later use, for example in a variable or a list, you have to get it out of the function by return or yield. (And yeah, please show your code so it's easier to give an answer to your actual problem.)
2nd Jan 2019, 8:59 AM
HonFu
HonFu - avatar