[英]Infinite loop in python from user input
I am writing Python code counting up to the number the user provides, but I get into an infinite loop when running the code. 我正在编写Python代码,计数到用户提供的数量,但是在运行代码时陷入无限循环。 Please note I tried commenting out lines 3 and 4 and replaced "userChoice" with a number, let's say for example 5, and it works fine.
请注意,我尝试注释掉第3行和第4行,并用数字代替了“ userChoice”,例如以5为例,它工作正常。
import time
print "So what number do you want me to count up to?"
userChoice = raw_input("> ")
i = 0
numbers = []
while i < userChoice:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
time.sleep(1)
print "The numbers: "
for num in numbers:
print num
time.sleep(1)
raw_input
returns a string, not int
. raw_input
返回一个字符串,而不是int
。 You can fix the issue by converting user response to int
: 您可以通过将用户响应转换为
int
来解决此问题:
userChoice = int(raw_input("> "))
In Python 2.x objects of different types are compared by the type name so that explains the original behavior since 'int' < 'string'
: 在Python 2.x中, 通过类型名称比较不同类型的对象,从而解释了自
'int' < 'string'
以来的原始行为:
CPython implementation detail: Objects of different types except numbers are ordered by their type names;
CPython实现细节:除数字外,其他类型的对象按其类型名称排序; objects of the same types that don't support proper comparison are ordered by their address.
不支持正确比较的相同类型的对象按其地址排序。
You are comparing a number with a string in: 您正在将数字与字符串进行比较:
while i < userChoice:
The string will always be greater than the number. 字符串将始终大于数字。 At least in Python 2 where these are comparable.
至少在可比较的Python 2中。
You need to turn userChoice
into a number: 您需要将
userChoice
转换为数字:
userChoice = int(raw_input("> "))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.