Skip to content
Advertisement

How to solve StopIteration error in Python?

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.)

def simpleGeneratorFun(n):

    while n<20:
        yield (n)
        n=n+1
    # return [1,2,3]

x = simpleGeneratorFun(1)
while x.__next__() <20:
    print(x.__next__())
    if x.__next__()==10:
        break

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:

def simpleGeneratorFun(n):

    while n<20:
        yield (n)
        n=n+1
    # return [1,2,3]

x = simpleGeneratorFun(1)
while True:
    try:
        val = next(x) # x.__next__() is "private", see @Aran-Frey comment 
        print(val)
        if val == 10:  
            break
    except StopIteration as e:
        print(e)
        break
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement