这是官方python文档中给出的用于打印Fibonacci系列的代码.
我不明白为什么这个代码运行到无穷大,因为while循环条件没有问题.
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a + b
number = raw_input("What's the number you want to get Fibonacci series up to?")
fib(number)
Run Code Online (Sandbox Code Playgroud)
您正在传递一个字符串fib,而它a是一个整数.在Python 2中,任何整数都小于任何字符串.
>>> 1000000000000000000000000000000000 < ""
True
>>> 3 < "2"
True
Run Code Online (Sandbox Code Playgroud)
用整数调用你的函数:
fib(int(number))
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python 3,那么尝试比较字符串和数字只会引发TypeError:
>>> "3" < 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
Run Code Online (Sandbox Code Playgroud)