Skip to main content
 首页 » 编程设计

python之为什么我看起来有一个无限循环

2025年05月04日10qq78292959

这是教程的一部分。我的目标是获取用户的输入,然后在条件为真时递增它。

inputNum = raw_input("What is max number?") 
 
def incrementF(greatest): 
    i = 0 
    numbers = [] 
 
    while i < greatest: 
        print "At the top of the list numbers is %d" % i 
        numbers.append(i) 
 
        i += 1 
        print "Numbers now: ", numbers 
        print "At the bottom i is %d" % i 
 
    print "The numbers:" 
 
    for num in numbers: 
        print num 
 
incrementF(inputNum) 

当我运行脚本并为 inputNum 输入任何内容,而不是几行输出时,我似乎遇到了无限循环。

例如,如果原始输入提示给了 10,我本以为会看到类似这样的内容:

At the top of the list numbers is 0, 
Numbers now: 0, 
0 
At the top of the list numbers is 1, 
Numbers now: 1, 
1 

我已经多次阅读我的脚本,但看不懂。我怀疑这可能与缩进有关?但我不确定。

请您参考如下方法:

在 docs 中引用对于 raw_input:

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

因此,greatest 将是一个字符串,因为您使用了 raw_input 来获取它。

此外,在 Python 2.x 中,字符串总是被评估为大于整数*:

>>> 1 < 'a' 
True 
>>> 100000000000 < 'a' 
True 
>>> 

这意味着您的 while 循环的条件将始终评估为 True,因为 greatest 将始终评估为大于 i .因此,你会得到一个无限循环。

您可以简单地通过将 greatest 设置为像 i 这样的整数来解决这个问题:

inputNum = int(raw_input("What is max number?")) 

*注意:如果您想了解更多信息,请参阅 How does Python compare string and int?