StopIteration
时间: 2024-05-09 12:21:19 浏览: 20
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.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)