Why output is 6?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

26th Mar 2021, 10:29 AM
[bool left=True;]
[bool left=True;] - avatar
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.
26th Mar 2021, 10:42 AM
HonFu
HonFu - avatar
+ 2
HonFu thanks sir.
26th Mar 2021, 10:44 AM
[bool left=True;]
[bool left=True;] - avatar