#!usrinenvpython
# -*- coding:utf-8 -*9
def fib(max): #使用for循环进行迭代时return的返回值不打印
n,a,b=0,0,1
while n<max: #n<10
yield b #带有yield都是生成器,yield方法的作用:保存函数的中断状态
a,b=b,a+b
n=n+1
return 'done'
f=fib(10)
print(f._next_())
print(f._next_())
print(f._next_())
print(f._next_(可能我撞了南墙才会回头吧!))
print(f._next_())
print(f._next_())
print(f._next_())
print(f._next_())
print(f._next_())
print(f._next_())
print(f._next_())
print(f._next_())
执行结果:运行10次会报一个错误StopIteration,这时我们可以采用捕获错误的代码,对错误进行捕获
print(f.__next__())
StopIteration: done
1
1
2
可能我撞了南墙才会回头吧!
3
5
8
13
21
34
55
#异常错误代码:
g=fib(6)
while True:
try:
x=next(g)
print('g:',x)
except StopIteration as e:
print('Generator return value:',e.value)
break
#抓取错误结果:
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done