StopIteration
` exception in Python :# Define a custom iterator
class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current < self.end:
result = self.current
self.current += 1
return result
else:
raise StopIteration
# Use the iterator to print numbers from 0 to 4
my_iterator = MyIterator(0, 5)
for num in my_iterator:
print(num)
0
1
2
3
4
MyIterator
` that generates numbers from a given start value to an end value. __next__()
` method is responsible for generating the next value in the iterator. When there are no more values to generate, we raise the `StopIteration
` exception. This tells the caller that the iterator has reached the end of its sequence. for
` loop to print numbers from 0 to 4. When the iterator reaches the end of its sequence, the `for
` loop stops iterating.