在Python中获得fibonacci系列中的无限循环

时间:2014-07-15 16:21:43

标签: python python-2.7 while-loop infinite-loop fibonacci

#Program to print fibonacci until a range.
print "Fibonacci Series"
print "Enter a range"
range = raw_input()
first=1
second =1
print first
print ", "
print second
print ", "
third = 0
while(third < range):
    third=first+second
    print third
    print ", "
    first = second
    second = third
#End of program

此处,程序会询问用户是否有范围并将该系列打印到该范围。但是,我得到了无限循环系列。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

range = raw_input()range设为字符串,例如它正在分配range = '5'而不是range = 5

因此,在Python 2.x *中,比较third < range将始终为True,因为整数总是比字符串少:

>>> 10 < '5'
True

最小修复是将输入转换为整数:

range = int(raw_input())

但是,请注意range is a built-in function,因此您应该为该变量选择一个不同的名称。

* 请注意,在3.x中将字符串与整数进行比较会导致错误:

>>> 10 < '5'
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    10 < '5'
TypeError: unorderable types: int() < str()