def Fib(n): ''' 假定序号为0或者1,返回1,序号为2时返回2 ''' before = 1 after = 1 for i in range(n): before, after = after, before + after return before for i in range(10): print(Fib(i))
用生成器实现如下:
def fib(n): before = 1 after = 1 for i in range(n): yield before before, after = after, before + after gen = fib(6) for i in gen: print(i)