Python看了一段时间了,对yield还是了解不透彻。
原来自定的函数里,含有yield的话,就变成了generator了,直接调用函数的话,是没有反应的。最后看一个视频的时候看到演示里面使用type()查看的到了是generator。才知道是怎么回事了。
对象是使用Fibonacii数列。
代码如下:
# -*- encoding = utf-8 -*-
import string
import sys
# continue ?
def isContinueDone():
propt = input("Continue?[Y/y, N/n]: ").strip()
if propt.isalpha:
if propt in ("Y", "y", "N", "n"):
if propt.lower() == "y":
fibonacii()
else:
print("Quit soon.")
sys.exit(0)
else:
print("Out of choice. try again.")
isContinueDone()
else:
print("Invalid choice, try again.")
isContinueDone()
# definied fibonacii method
def fibonaciiAlgorithm(max):
n, a, b = 0, 0, 1
while n=1]: ").strip()
if propt.isdigit():
num = int(propt)
if num < 1:
print("Specified number is out of range. try again.")
fibonacii()
else:
number = fibonaciiAlgorithm(num)
for tmp_num in number:
pass
isContinueDone()
else:
print("Invalid number...try again.")
fibonacii()
if __name__ == '__main__':
fibonacii()
测试结果如下:
Enter number[>=1]: 10
10-th fibonacii number is 55
Continue?[Y/y, N/n]: y
Enter number[>=1]: 12
12-th fibonacii number is 144
Continue?[Y/y, N/n]: 10
Out of choice. try again.
Continue?[Y/y, N/n]: y
Enter number[>=1]: 1
1-th fibonacii number is 1
Continue?[Y/y, N/n]: y
Enter number[>=1]: 2
2-th fibonacii number is 1
Continue?[Y/y, N/n]: y
Enter number[>=1]: 3
3-th fibonacii number is 2
Continue?[Y/y, N/n]: y
Enter number[>=1]: 4
4-th fibonacii number is 3
Continue?[Y/y, N/n]: y
Enter number[>=1]: 5
5-th fibonacii number is 5
Continue?[Y/y, N/n]: y
Enter number[>=1]: 6
6-th fibonacii number is 8
Continue?[Y/y, N/n]: y
Enter number[>=1]: 7
7-th fibonacii number is 13
Continue?[Y/y, N/n]: y
Enter number[>=1]: 8
8-th fibonacii number is 21
Continue?[Y/y, N/n]: y
Enter number[>=1]: 9
9-th fibonacii number is 34
Continue?[Y/y, N/n]: y
Enter number[>=1]: 10
10-th fibonacii number is 55
Continue?[Y/y, N/n]: y
Enter number[>=1]: 11
11-th fibonacii number is 89
Continue?[Y/y, N/n]: y
Enter number[>=1]: 12
12-th fibonacii number is 144
Continue?[Y/y, N/n]: n
Quit soon.