你能从循环外打破 while 循环吗?

Can you break a while loop from outside the loop?

你能从循环外打破 while 循环吗?这是我正在尝试做的一个(非常简单的)示例:我想在 While 循环内请求连续,但是当输入为 'exit' 时,我希望 while 循环中断!

active = True

def inputHandler(value):
    if value == 'exit':
        active = False

while active is True:
    userInput = input("Input here: ")
    inputHandler(userInput)

是的,您确实可以那样做,只需稍作调整:使 active 全局化。

global active
active = True

def inputHandler(value):
    global active
    if value == 'exit':
        active = False

while active:
    userInput = input("Input here: ")
    inputHandler(userInput)

(我也将 while active is True 改为 while active 因为前者是多余的。)

在您的例子中,在 inputHandler 中,您正在创建一个名为 active 的新变量并将 False 存储在其中。这不会影响模块级别 active.

要解决此问题,您需要明确说明 active 不是新变量,而是在模块顶部使用 global 关键字声明的变量,如下所示

def inputHandler(value):
    global active

    if value == 'exit':
        active = False

但是,请注意,执行此操作的正确方法是 return inputHandler 的结果并将其存储回 active

def inputHandler(value):
    return value != 'exit'

while active:
    userInput = input("Input here: ")
    active = inputHandler(userInput)

如果您查看 while 循环,我们使用了 while active:。在 Python 中,您要么必须使用 == 来比较值,要么只依赖于值的真实性。 is 运算符仅在需要检查值是否相同时使用。


但是,如果你完全想避免这种情况,你可以简单地使用 iter 函数,它会在满足标记值时自动中断。

for value in iter(lambda: input("Input here: "), 'exit'):
    inputHandler(value)

现在,iter 将继续执行传递给它的函数,直到函数 returns 传递给它的标记值(第二个参数)。

其他人已经说明了您的代码失败的原因。或者,您可以将其分解为一些非常简单的逻辑。

while True:
    userInput = input("Input here: ")
    if userInput == 'exit':
        break