使用特定输入结束 while 循环

Ending a while loop with a specific input

我曾尝试搜索类似的问题,但没有找到。我试图让 while 循环在输入 'done' 时停止。无论我做什么或如何格式化它,它都不会停止循环,或者打印我分配给 'done' 的值。如果我 运行 它没有赋值,它会抛出一个 'NameError: name 'done' is not defined'。如果我给它赋值,它不会结束循环。我不是在寻求代码优化或其他任何帮助,但如果有人能解释为什么会这样,我将不胜感激。

Counter1 = 0   
Counter2 = 0
Counter3 = 0
Counter4 = 0
n = 0
while True:  #Begins a loop that runs until manually ended.   
        n = input("Enter desired scores, and type done when complete: ")
        if n == "done":  #Closes the loop if given this input.
                break
        else:
                n = int(n) #changes input to an integer
        if n >= 0 and n <= 25:    #increments the counters depending on the input
                Counter1 = Counter1 + 1
        elif n > 25 and n <= 50:
                Counter2 = Counter2 + 1
        elif n > 50 and n <= 75:
                Counter3 = Counter3 + 1
        else:
                Counter4 = Counter4 + 1

您正在使用 Python 2. input 立即尝试将您的输入转换为 Python 类型,这是 危险的 并且会导致您遇到的问题。请改用 raw_input

换句话说,当您键入 "done" 时,input 会尝试 eval* 它,得到一个名为 "done" 的不存在的变量,然后放弃出去抱怨。如果您改用 raw_input ,它将为您提供一个字符串,您可以根据需要将其正确地转换为不同的类型,或者在您的情况下,不要管它,因为字符串就是您想要的。

* 这是关于 JavaScript 但 eval 出现在许多编程语言中。