简体   繁体   English

python中的无限while循环

[英]Infinite while loop in python

No matter what I do, I can't get this while loop to work; 无论我做什么,都无法使while循环正常工作。 unless i hardcode the value in. 除非我对值进行硬编码。

count = 0
value = raw_input('How many?')
print value
while (count <= value):
        print "a"
        count= count + 1

At first I tried using a command line argument, using sys.argv[1] for value but I got the same problem. 最初,我尝试使用命令行参数,使用sys.argv [1]作为值,但是遇到了同样的问题。 This seems so simple, yet I cannot for the life of me figure out what I'm doing wrong. 这似乎很简单,但是我无法终生弄清楚自己在做什么错。

Ensure that value is an integer, 确保该值为整数,

while (count <= int(value)):
    count= count + 1

By default raw_input is a string, and for every integer n and every string s we have n<s is True (!), hence your loop (without the int ) never breaks. 默认情况下, raw_input是一个字符串,对于每个整数n和每个字符串s我们拥有n<s is True (!),因此您的循环(不带int )将永不中断。

Note: In Python 3 comparing string and integers will give a TypeError: unorderable types: str() < int() , which is probably more "expected" behaviour. 注意:在Python 3中,比较字符串和整数将给出TypeError: unorderable types: str() < int() ,这可能更“预期”。

Convert your input to an integer first 首先将您的输入转换为整数

value = int(raw_input('How many?'))
print value

By the way, if you really want to get your statement to be value times printed change condition from 顺便说一句,如果您真的想让您的陈述成为value乘以印刷变更条件,

count <= int(value)

to

count < int(value)

or start count from 1 或从1开始count

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

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