小编sai*_*ran的帖子

python 中生成器函数引发的 StopIteration 异常处理

这是我的生成器函数代码:

def fibo():
    n1=0
    n2=1
    while True:
        if n1 == 8:
            raise StopIteration
        else:
            yield n1
            n1,n2=n2,n1+n2
        
seq=fibo()
Run Code Online (Sandbox Code Playgroud)

这是我用于生成序列的代码版本 1:

for ele in seq:
    print(next(seq))
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
5

RuntimeError: generator raised StopIteration
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-3-c01815b93e23> in fibo()
      5         if n1 == 8:
----> 6             raise StopIteration
      7         else:

StopIteration: 

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
<ipython-input-3-c01815b93e23> in <module>
     11 seq=fibo()
     12 
---> 13 …
Run Code Online (Sandbox Code Playgroud)

python iterator yield generator python-3.x

2
推荐指数
1
解决办法
5842
查看次数

标签 统计

generator ×1

iterator ×1

python ×1

python-3.x ×1

yield ×1