Junior — Middle
What exception is raised when an iteration loop is terminated?
sobes.tech AI
Answer from AI
In Python, to stop the execution of an iteration loop when traversing an iterator, the StopIteration exception is raised. This exception is automatically raised when the iterator is exhausted, and it is usually handled by the for loop itself.
Example:
iterator = iter([1, 2, 3])
while True:
try:
item = next(iterator)
print(item)
except StopIteration:
break
Here, StopIteration signals that there are no more elements, and the loop terminates.