+ 1
Someone please explain this problem
def count_to_5(): for i in range(1,6): yield(i) c = count_to_5() n = 0 for i in c: n += 1 for i in c: n -= 1 print(n) #Output: 5 #Why and how output is 5?
1 Réponse
+ 5
A generator will no longer yield once it had completed generating. So your second attempt to read from it (where you decremented <n> by 1) is of no effect, and <n> will still have 5 as its value.
To verify this, add print( n ) underneath the line decrementing <n> in the second for...in loop.