为什么我的代码会进入无限循环?

时间:2016-01-04 20:05:25

标签: python python-2.7 while-loop infinite-loop

我是学习Python的新手。我无法弄清楚为什么我的代码会运行到无限循环中。

我只是尝试使用while循环打印数字,并使用函数调用while循环。 感谢您的帮助!

以下是代码:

numbers = []

def check_num(i, end_num):
    while i < end_num:
        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


k = raw_input(">")
check_num(0, k)

print "The numbers: "
print check_num

for num in numbers:
    print num

1 个答案:

答案 0 :(得分:4)

raw_input为您提供了一个字符串。

变化:

k = raw_input(">")

成:

k = int(raw_input(">"))

因为在Python 2中你可以比较字符串和数字:

>>> 2 < '1'
True

幸运的是,这在Python 3中不起作用:

>>> 2 < '1'
...
TypeError: unorderable types: int() < str()

所以在你的情况下end_num是一个字符串。因此,无论整数i < end_num的值是多少,i都将始终为真。所以,你的循环:

while i < end_num:

永远不会终止。