I have just read a bunch of posts on how to handle the StopIteration error in Python, I had trouble solving my particular example.I just want to print out from 1 to 20 with my code but it prints out error StopIteration. My code is:(I am a completely newbie here so please don’t block me.)
JavaScript
x
13
13
1
def simpleGeneratorFun(n):
2
3
while n<20:
4
yield (n)
5
n=n+1
6
# return [1,2,3]
7
8
x = simpleGeneratorFun(1)
9
while x.__next__() <20:
10
print(x.__next__())
11
if x.__next__()==10:
12
break
13
Advertisement
Answer
Any time you use x.__next__()
it gets the next yielded number – you do not check every one yielded and 10 is skipped – so it continues to run after 20 and breaks.
Fix:
JavaScript
1
18
18
1
def simpleGeneratorFun(n):
2
3
while n<20:
4
yield (n)
5
n=n+1
6
# return [1,2,3]
7
8
x = simpleGeneratorFun(1)
9
while True:
10
try:
11
val = next(x) # x.__next__() is "private", see @Aran-Frey comment
12
print(val)
13
if val == 10:
14
break
15
except StopIteration as e:
16
print(e)
17
break
18