【问题标题】:Break out of a while loop using a function使用函数打破while循环
【发布时间】:2013-10-17 11:39:30
【问题描述】:

有没有办法使用函数来打破无限循环?例如,

# Python 3.3.2
yes = 'y', 'Y'
no = 'n', 'N'
def example():
    if egg.startswith(no):
        break
    elif egg.startswith(yes):
        # Nothing here, block may loop again
        print()

while True:
    egg = input("Do you want to continue? y/n")
    example()

这会导致以下错误:

SyntaxError: 'break' outside loop

请解释为什么会发生这种情况以及如何解决。

【问题讨论】:

    标签: python python-3.x user-defined-functions break


    【解决方案1】:

    就我而言,你不能在 example() 中调用 break,但你可以让它返回一个值(例如:一个布尔值)以停止无限循环 p>

    代码:

    yes='y', 'Y'
    no='n', 'N'
    
    def example():
        if egg.startswith(no):
            return False # Returns False if egg is either n or N so the loop would break
        elif egg.startswith(yes):
            # Nothing here, block may loop again
            print()
            return True # Returns True if egg is either y or Y so the loop would continue
    
    while True:
        egg = input("Do you want to continue? y/n")
        if not example(): # You can aslo use "if example() == False:" Though it is not recommended!
            break
    

    【讨论】:

      【解决方案2】:

      结束 while-true 循环的方法是使用break。此外,break 必须在循环的直接范围内。否则,您可以利用异常将堆栈中的控制权交给处理它的任何代码。

      然而,通常值得考虑另一种方法。如果您的示例实际上接近您真正想要做的,即取决于一些用户提示输入,我会这样做:

      if raw_input('Continue? y/n') == 'y':
          print 'You wish to continue then.'
      else:
          print 'Abort, as you wished.'
      

      【讨论】:

      • +1 用于在需要复杂嵌套时使用异常。一个真实的例子是迭代器在完成时引发的StopIteration 异常。
      【解决方案3】:

      在循环内跳出函数的另一种方法是在函数内raise StopIteration,并在函数外except StopIteration循环。这将导致循环立即停止。例如,

      yes = ('y', 'Y')
      no = ('n', 'N')
      
      def example():
          if egg.startswith(no):
              # Break out of loop.
              raise StopIteration()
          elif egg.startswith(yes):
              # Nothing here, block may loop again.
              print()
      
      try:
          while True:
              egg = input("Do you want to continue? y/n")
              example()
      except StopIteration:
          pass
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        • 1970-01-01
        • 2018-03-23
        • 2020-10-21
        • 2016-02-24
        相关资源
        最近更新 更多