StopIteration
时间: 2024-05-09 15:21:19 浏览: 72
禁止系统重复运行
StopIteration is a built-in Python exception that is raised when the iterator has no more items to iterate over. It is used to signal the end of the iteration. When a sequence is exhausted and there are no more items to be returned, the __next__() method of the iterator raises the StopIteration exception.
For example, consider the following code that uses an iterator to iterate over a list of numbers:
```
numbers = [1, 2, 3, 4, 5]
iter_numbers = iter(numbers)
while True:
try:
num = next(iter_numbers)
print(num)
except StopIteration:
break
```
In this code, we create an iterator for the list of numbers using the iter() function. We then use a while loop to iterate over the numbers using the next() function until the StopIteration exception is raised, at which point the loop is terminated.
阅读全文