Your code should look like this
Code:
def gen(): for i in range(5): yield i count=gen() for i in count: print i
output:
0 1 2 3 4
Notes:
When you loop for i in count , you are trying to get the next element again here count.next() , you are trying to get the second element. So you are trying to get the +2 element from the current position
So what happens in your code is the following:
:
1. for i in count here we get the following value, which is 0
2. print count.next() is called again and the next value is printed, so 1 is printed
3. for i in count here the next value is called again, which is 2
4. print count.next() is called again here and the next value is printed, so 3 is printed
5. for i in count , the following value is again called here: 4
6. Finally, you call print count.next() since there is no value in the generator. You specified a StopIteration exception
source share