How to Prevent Iteration to Go On Forever in Python


In this example we will show how to prevent the iteration to go on forever using the StopIteration statement in Python.

Source Code

class MySquare:
    def __init__(self, x):
        self.x = x

    def __iter__(self):
        return self

    def __next__(self):
        self.x = self.x ** 2
        if self.x < 999999999999:
            return self.x
        else:
            raise StopIteration


my_square = MySquare(2)
my_iter = iter(my_square)

for i in my_iter:
    print(i)

Output:

4
16
256
65536
4294967296
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments