为什么我的python程序与while循环无限运行

时间:2017-03-15 14:23:24

标签: python

这是官方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)

2 个答案:

答案 0 :(得分:7)

您正在将字符串传递给fib,而a是一个整数。在Python 2中,任何整数小于任何字符串。

>>> 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'

答案 1 :(得分:1)

Raw_input给出一个字符串,以便将字符串与int进行比较。

相关问题