0
What is yields for excately?
Why this: def countdown(): i=5 while i > 0: yield i i -= 1 for i in countdown(): print(i) Instead of this: def countdown(): i = 6 while i > 0: i -= 1 print(i) The first one was to explain how yield works, i just miss the point why we don't use the second solution instead of it?
3 Answers
+ 2
First solution use for "lazy evaluation". It this saves memory and is often used in real projects.
+ 1
Yield allows you to create a number of results pertaining to your definition.
Remember, Return will only produce one result.
Back to Yield - So you need a number of results, but instead of printing these results, you may wish to operate upon them later in the code, possibly only printing out those results which are still valid.
Using yield instead of print gives you more control over your final output configuration.
+ 1
Thanks a lot guys! I need to learn a lot...