【问题标题】:Can you break a while loop from outside the loop?你能从循环外打破一个while循环吗?
【发布时间】:2015-11-25 01:05:48
【问题描述】:

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

active = True

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

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

【问题讨论】:

  • while active: 或者如果你坚持while active == True: 但不是is True
  • 更好的方法:raise 一些异常,调用sys.exit,让whilecondition 本身检查输入(可能使用另一个函数)

标签: python python-3.x while-loop boolean-expression


【解决方案1】:

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

要解决这个问题,您需要明确指出 active 不是一个新变量,而是在模块顶部声明的变量,使用 global 关键字,像这样

def inputHandler(value):
    global active

    if value == 'exit':
        active = False

但是,请注意,正确的做法是返回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 将继续执行传递给它的函数,直到函数返回传递给它的标记值(第二个参数)。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      是的,您确实可以这样做,只需稍作调整:将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,因为前者是多余的。)

      【讨论】:

      • 当你没有 global active 时,python 会创建一个仅存在于 inputHandler 函数内部的局部变量 active
      猜你喜欢
      • 2020-10-21
      • 2018-03-23
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 2012-02-14
      • 2021-05-02
      • 2011-09-06
      相关资源
      最近更新 更多