著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:1, 1, 2, 3, 5, 8, 13, 21, 34, ...
使用循环实现:
def fib(max):
n,a,b=0,0,1
while n<max:
print(b)
a,b=b,a+b
n=n+1
return 'over'
k=fib(10)
使用生成器实现:
def fib(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,a+b
n=n+1
return 'done'
g=fib(10)
while True:
try:
x=next(g)
print('g',x)
except StopIteration as e:
print('Generator return value:',e.value)
break