在 Python 中获得斐波那契数列中的无限循环 [英] Getting infinite loop in fibonacci series in Python
问题描述
#Program 打印斐波那契直到一个范围.打印斐波那契数列"打印输入一个范围"范围 = raw_input()第一个=1第二 =1先打印打印 ", "打印第二个打印 ", "第三个 = 0而(第三个<范围):第三=第一+第二打印第三个打印 ", "第一 = 第二第二 = 第三#程序结束
在这里,程序要求用户输入一个范围并打印该范围内的系列.但是,我得到了无限循环的系列.有人可以帮我吗?
range = raw_input()
将 range
设置为 string,例如它正在分配 range = '5'
而不是 range = 5
.
比较第三个<因此,在 Python 2.x * 中 range
将始终为 True
,因为整数总是小于字符串的比较:
最小的解决方法是将输入转换为整数:
range = int(raw_input())
但是,请注意 range
是一个内置的-在函数中,所以你应该为那个变量选择一个不同的名字.
* 注意,在 3.x 中比较字符串和整数会导致错误:
<预><代码>>>>10<'5'回溯(最近一次调用最后一次):文件<pyshell#0>",第 1 行,在 <module> 中10<'5'类型错误:无法排序的类型:int() <字符串()#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
Here, the program asks user for a range and prints the series upto the range. But, m getting the series of infinite loop. Can anyone help me?
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()
这篇关于在 Python 中获得斐波那契数列中的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!