fibonacci.py源代码分析

"""Fibonacci sequences using generators

This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""

__author__ = "Mark Pilgrim ([email protected])"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2004 Mark Pilgrim"
__license__ = "Python"

def fibonacci(max):
a, b = 0, 1

%将a赋为0,b赋为1
while a < max:
yield a

%特别注意此处的yield:yield每执行一次,将把它后面的参数记住,打个比方,有点类似于数据结构 里面的栈,将a压入栈,每执行一次yield,将a的值压入一次
a, b = b, a+b

%fibonacci算法的规律

for n in fibonacci(1000):
print n,

%将fibonacci(1000)中yield存储的1000个a的值全部打印出来。

你可能感兴趣的:(python学习)