Skip to main content
 首页 » 编程设计

python之python中的无限while循环

2025年05月04日9thcjp

无论我做什么,我都无法让这个 while 循环工作;除非我硬编码值。

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

起初我尝试使用命令行参数,使用 sys.argv[1] 作为值,但我遇到了同样的问题。这看起来很简单,但我无法终生弄清楚我做错了什么。

请您参考如下方法:

确保值是一个整数,

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

默认 raw_input是一个字符串,并且对于每个整数 n和每个字符串 s我们有n<s is True (!),因此您的循环(没有 int)永远不会中断。

注意:在 Python 3 中比较字符串和整数将得到 TypeError: unorderable types: str() < int() ,这可能是更“预期”的行为。