当生成器函数中含有return时,return不会返回任何值,会直接终止当前生成器,对yield的作用没有影响,当函数执行到return时候,调用next()来执行生成器则会报错,如果使用for循环遍历,for循环会自动捕获该异常,直接停止遍历

def func():
    for i in range(10):
        i += 1
        yield i
        # print(i)
        return i
f = func()
for i in f:
    print(i)
f = func()
next(f)
# f.send(2)
next(f)
next(f)
next(f)

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-25
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
猜你喜欢
  • 2021-11-19
  • 2022-02-08
  • 2021-08-26
  • 2021-10-08
  • 2022-02-21
  • 2022-01-11
相关资源
相似解决方案