使用迭代器来生成斐波那契数列
# -*- coding:utf-8 -*-
# 这是一个特殊的迭代器(生成器)
def creat_num(number):
a, b = 0, 1
while True:
ret = yield a # ret接收返回值
print(">>>ret>>>", ret)
a, b = b, a + b
number -= 1
if number < 1:
break
def main():
ret = creat_num(4) # 限制四个数
print(next(ret)) # 0
# 除了next能使用生成器以外,send也可以使用生成器,并且有返回值
x = ret.send('nihai') # >>>ret>>> nihai
print(x) # 1
x = ret.send('nihao') # >>>ret>>> nihao
print(x) # 1
x = ret.send('nihao') # >>>ret>>> nihao
print(x) # 2
if __name__ == '__main__':
main()