在Python的斐波那契数列中获取无限循环 [英] Getting infinite loop in fibonacci series in Python

查看:111
本文介绍了在Python的斐波那契数列中获取无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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

在这里,程序要求用户输入一个范围,然后将系列打印到该范围.但是,m得到了一系列无限循环.谁能帮我吗?

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()range设置为字符串,例如它分配的是range = '5'而不是range = 5.

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

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

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

但是,请注意 range是内置函数,因此您应该为该变量选择一个不同的名称.

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

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

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

这篇关于在Python的斐波那契数列中获取无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆