使用 生成器(yield) 获取斐波拉契数。
代码如下:
def fun(n): a,b,c = 0,0,1 while a < n: yield b # b, c = c, b + c 以下代码可以用此替换 t = (c, b + c) b = t[0] c = t[1] a += 1 n = int(input('您想获取前几位斐波拉契数? ')) for index,i in enumerate(fun(n)): print('第{}位斐波拉契数是:{}'.format(index+1,i))
执行结果: