+ 2
Why is the output of the code :5 ?It should be zero right?
8 Respuestas
+ 5
Becouse yours second loop don’t work when you use yield in your function.yield it is a generator and generators you can use one time.
+ 3
The code that is needed to run this task properly is:
def count_to_5():
for i in range(1,6):
yield (i)
c=count_to_5()
for i in c:
print(i)
So "c" is a generator object. It stays connected with the function. You can only iterate once over it, then it is exhausted.
If you don't wanted the generator to iterate in a loop, you can get result by calling:
next(c)
Each time this is called, a new number of the result will be given. If you call more than the generator can give back, you will run in a StopIteration Exception. A generator has no length, as it does not have any data stored.
+ 2
Thanks
+ 2
read about generator and itaerator necessarily
+ 2
What does next(c) do?
+ 2
Because of generator ..... only first for loop consider.....so n+=1 but not n -=1
+ 1
Yes
+ 1
next(c) does exctly do one step in iteration. You can trigger this in your code, but mostly iteration is done in a for loop.