How to solve StopIteration error in Python?

19,341

Solution 1

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

Solution 2

First, in each loop iteration, you're advancing the iterator 3 times by making 3 separate calls to __next__(), so the if x.__next__()==10 might never be hit since the 10th element might have been consumed earlier. Same with missing your while condition.

Second, there are usually better patterns in python where you don't need to make calls to next directly. For example, if you have finite iterator, use a for loop to automatically break on StopIteration:

x = simpleGeneratorFun(1)
for i in x:
    print i
Share:
19,341
Barish Ahsen
Author by

Barish Ahsen

Updated on June 06, 2022

Comments

  • Barish Ahsen
    Barish Ahsen almost 2 years

    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