+ 2

Why is the output of the code :5 ?It should be zero right?

https://code.sololearn.com/cr5UFRBePumq/?ref=app

13th May 2020, 2:33 PM
Alen Antony
Alen Antony - avatar
8 odpowiedzi
+ 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.
13th May 2020, 3:00 PM
💡Arno Gevorgyan 🐍
💡Arno Gevorgyan 🐍 - avatar
+ 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.
13th May 2020, 7:02 PM
Lothar
Lothar - avatar
+ 2
Thanks
13th May 2020, 3:38 PM
Alen Antony
Alen Antony - avatar
+ 2
read about generator and itaerator necessarily
13th May 2020, 3:40 PM
💡Arno Gevorgyan 🐍
💡Arno Gevorgyan 🐍 - avatar
+ 2
What does next(c) do?
14th May 2020, 1:51 AM
Alen Antony
Alen Antony - avatar
+ 2
Because of generator ..... only first for loop consider.....so n+=1 but not n -=1
14th May 2020, 7:24 PM
Nidhi Verma
+ 1
Yes
13th May 2020, 3:42 PM
Alen Antony
Alen Antony - avatar
+ 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.
14th May 2020, 10:36 AM
Lothar
Lothar - avatar