Getting infinite loop in fibonacci series in Python

前端 未结 1 1418
花落未央
花落未央 2021-01-25 09:11
#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         


        
相关标签:
1条回答
  • 2021-01-25 10:01

    range = raw_input() sets range to be a string, e.g. it is assigning range = '5' rather than range = 5.

    The comparison third < range will therefore always be True in Python 2.x *, as integers always compare less than strings:

    >>> 10 < '5'
    True
    

    The minimal fix is to convert the input to an integer:

    range = int(raw_input())
    

    However, note that range is a built-in function, so you should pick a different name for that variable.

    * Note that in 3.x comparing a string with an integer causes an error:

    >>> 10 < '5'
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        10 < '5'
    TypeError: unorderable types: int() < str()
    
    0 讨论(0)
提交回复
热议问题