使用yield(生成器)实现斐波那契数列

import sys

# 生成器函数--斐波那契
def fibonacci(n):
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n):
            return
        yield a
        a, b = b, a+b
        counter += 1

f = fabonacci(10)  # f是一个迭代器,由生成器返回生成

while True:
    try:
        print(next(f), end="")
    except StopIteration:  # StopIteration异常用于标识迭代完成,防止出现无限循环的情况。
        sys.exit()

  

原文地址:https://www.cnblogs.com/zijue/p/14184643.html