Python中的while循环无法退出

3 投票
4 回答
5667 浏览
提问于 2025-04-17 12:17

我现在正在自学Python,正在用《Learn Python The Hard Way》里的练习来帮助自己。

目前,我在做一个关于“while循环”的练习,具体是把一个在脚本中能正常工作的while循环转换成一个函数,然后在另一个脚本中调用这个函数。这个程序的唯一目的是往一个列表里添加项目,然后逐步打印出这个列表。

我遇到的问题是,一旦我调用这个函数,里面的循环就开始无限循环下去了。

我已经多次分析我的代码(见下方),但找不到明显的错误。

def append_numbers(counter):
    i = 0
    numbers = []

    while i < counter:
        print "At the top i is %d" % i
        numbers.append(i)

        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

count = raw_input("Enter number of cycles: ")

print count
raw_input()

append_numbers(count)

4 个回答

-1

上面已经解释了为什么这个while循环会一直运行。它循环了很多次(因为ASCII码的值很大)

不过,要解决这个while循环的问题,你可以简单地:

while i<int(counter):
    print "At the top i is %d" % i
    numbers.append(i)
1

把输入的字符串转换成整数... count=int(count)

15

我觉得你想要的是这个。

count = int(raw_input("Enter number of cycles: "))

如果你不把输入转换成整数,count 变量里就会存一个字符串。比如,当程序让你输入时,如果你输入了 1,那么 count 里存的就是 '1'(带引号的)。

字符串和整数比较的时候,结果会是 False。所以在 while i < counter: 这个条件里,永远会是 False,因为 i 是整数,而 counter 在你的程序里是字符串。

在你的程序中,如果你用 print repr(count) 来检查 count 变量的值,你就能自己发现这个问题。比如,当你输入 1 的时候,它会显示 '1'。而如果你按照我建议的修复方法去做,它就会显示 1(没有引号的)。

撰写回答