0
Help with challenge problem
https://code.sololearn.com/c4TZQ4FZlRUh/?ref=app I got this challenge problem wrong and Iâm really confused on how the answer is 5. Can you explain what for i in c means? If you substitute in the function, you would get for i in for i in range(1,6), which doesnât make any sense to me. How many times is that function being looped through? Also, why isnât the second for i in c function being looped through?
1 Answer
+ 1
The yield function returns a generator and generators can only be iterated over once.
When you store count_to_five() in c, what youâre actually storing is a generator object. You iterate over this generator once in your first for loop but then the second for loop is not executed because you have already iterated over the generator. Thatâs the reason why the count results 5 instead of going back to zero. You can insert some prints in order to better visualize your codeâs behavior.
Yield and generators are very well explained here: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do