使用 yield 实现斐波那契数列

 1 #!/usr/bin/python3
 2  
 3 import sys
 4  
 5 def fibonacci(n): # 生成器函数 - 斐波那契
 6     a, b, counter = 0, 1, 0
 7     while True:
 8         if (counter > n):
 9             return
10         yield a
11         a, b = b, a + b
12         counter += 1
13 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
14  
15 while True:
16     try:
17         print (next(f), end=" ")
18     except StopIteration:
19         sys.exit()
原文地址:https://www.cnblogs.com/zmh-980509/p/13025224.html