繁体   English   中英

来自用户输入的python中的无限循环

[英]Infinite loop in python from user input

我正在编写Python代码,计数到用户提供的数量,但是在运行代码时陷入无限循环。 请注意,我尝试注释掉第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返回一个字符串,而不是int 您可以通过将用户响应转换为int来解决此问题:

userChoice = int(raw_input("> "))

在Python 2.x中, 通过类型名称比较不同类型的对象,从而解释了自'int' < 'string'以来的原始行为:

CPython实现细节:除数字外,其他类型的对象按其类型名称排序; 不支持正确比较的相同类型的对象按其地址排序。

您正在将数字与字符串进行比较:

while i < userChoice:

字符串将始终大于数字。 至少在可比较的Python 2中。

您需要将userChoice转换为数字:

userChoice = int(raw_input("> "))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM