标签:## stop 否则 max pyc 式表 ack logs 异常
斐波那契数列并不能用列表生产式表示,但能够用函数得出:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 def fib(max): 4 n,a,b = 0,0,1 5 while n < max: 6 print(b) 7 a,b = b,a + b #初始a=0、b=1,a=b和b=a+b可理解为同时执行,即a=1、b=0+1=1 8 n = n +1 9 return ‘OK‘ 10 11 fib(9)
输出:
1
1
2
3
5
8
13
21
34
##################################华丽的分割线##########################################
将以上生成斐波拉契数列函数中的print (b)改为yield b则变成生成器
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 def fib(max): 4 n,a,b = 0,0,1 5 while n < max: 6 yield b 7 a,b = b,a + b 8 n = n + 1 9 return ‘OK‘ 10 11 fib(9)
print(fib(9))输出:
<generator object fib at 0x00000000010E6A40>
##################################华丽的分割线##########################################
1 f = fib(9) 2 print(f.__next__()) 3 print(f.__next__()) 4 print(f.__next__()) 5 print(f.__next__()) 6 print(f.__next__()) 7 print(f.__next__()) 8 print(f.__next__()) 9 print(f.__next__()) 10 print(f.__next__()) 11 print(f.__next__()) 12 print(f.__next__()) 13 print(f.__next__())
使用next方法调用要注意调用次数,否则会出现报错 或 使用异常处理
1
1
2
3
5
8
13
21
34
Traceback (most recent call last):
File "C:/Users/chenshiyang/PycharmProjects/5.py", line 24, in <module>
print(f.__next__())
StopIteration: OK
##################################华丽的分割线##########################################
加入异常处理玩法:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 def fib(max): 4 n,a,b = 0,0,1 5 while n < max: 6 yield b 7 a,b = b,a + b 8 n = n + 1 9 return ‘Finish‘ 10 11 f = fib(9) 12 while True: 13 try: 14 x = next(f) 15 print(‘f:‘,x) 16 except StopIteration as e: 17 print(‘已经到头了‘, e.value) 18 break
输出:
f: 1
f: 1
f: 2
f: 3
f: 5
f: 8
f: 13
f: 21
f: 34
已经到头了 Finish
标签:## stop 否则 max pyc 式表 ack logs 异常
原文地址:http://www.cnblogs.com/csy113/p/7632032.html