+ 1
Why output is 6??
def count_to_5(): for i in range(6): yield i n=0 c=count_to_5() for i in c: n+=1 for i in c: n-=1 print(n) #when i use the function name instead of c variable directly in both for loops the output becomes 0.
2 Answers
+ 5
Your function is a generator function.
Those create a so-called generator object, that dishes out the values one after another, either by using the next function or for example by looping over it.
You have to imagine those objects like vending machines: After they're empty, no coke will come out.
With your first loop, you empty c, so when you loop over it again, nothing happens, because your generator object is already empty.
So the loop just aborts directly, and n doesn't change any further.
+ 2
HonFu thanks sir.