gpt4 book ai didi

python - 在Python中获取斐波那契数列的无限循环

转载 作者:行者123 更新时间:2023-12-01 05:07:19 26 4
gpt4 key购买 nike

#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

这里,程序询问用户一个范围并打印该范围内的系列。但是,我得到了无限循环的序列。谁能帮我吗?

最佳答案

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

比较third < range因此将永远是True在 Python 2.x * 中,因为整数比较的总是小于字符串:

>>> 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()

关于python - 在Python中获取斐波那契数列的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24763326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com