进行比较
这是用于打印fibonacci系列的Python官方文档中给出的代码。
我不明白为什么此代码会运行到无穷大,因为循环条件还可以。
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)
您将字符串传递给fib
,而a
是整数。在Python 2中,任何整数都小于任何 string。
>>> 1000000000000000000000000000000000 < ""
True
>>> 3 < "2"
True
使用整数调用您的功能:
fib(int(number))
如果您使用的是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'
raw_input给出一个字符串,因此您将字符串与int。