【问题标题】:How to stop all code after Breaking nested loops打破嵌套循环后如何停止所有代码
【发布时间】:2023-11-30 20:06:01
【问题描述】:

为什么在从循环中断后执行额外的代码。我想停止代码并修改一些输入,但代码在中断后继续并给我一个错误。

if condition:
    for i in range(n):  
        if another condition:
            do_somthing
        else:
            flag = True
    
    for i in range(n: 
        if condition:
            do_something
        else:
            flag = True

    while flag:
        try:
            print('Erorr')
            break
        except:
            break
    # if break, I don't want to execute the rest of the code
    t = []
    for i in range(0, n):
        t.append(i)

【问题讨论】:

    标签: python loops try-catch break


    【解决方案1】:

    break 语句终止包含它的循环(在本例中为 try/except。)

    程序的控制流到循环体之后的语句。

    如果break 语句在嵌套循环内(在另一个循环内循环),break 语句将终止最内层循环。

    【讨论】:

      【解决方案2】:

      Break 不会停止代码,它会跳出循环。如果你想停止执行,你应该引发一个异常。

      如果您仍想运行一些其他内容,但想跳过您评论的部分,您可以使用else 语句。

      while flag:
          # do something here
      else:
          # this will only be executed if the while does not break
      

      https://docs.python.org/3/reference/compound_stmts.html#the-for-statement

      """ 在第一个套件中执行的 break 语句终止循环而不执行 else 子句的套件。在第一个套件中执行的 continue 语句会跳过套件的其余部分并继续下一项,如果没有下一项,则使用 else 子句。 """

      例如

      import random
      
      flag = True
      cnt  = 0
      while flag:
          
          # do something here
      
          cnt += 1
          val = random.randint(0, 10)
          if val > 8:
              break
      
          if val < 2:
              raise Exception("Raised an exception")
      
          if cnt > 5:
              flag = False
      
      else:
          # this will only be executed if the while does not break
          print("You ran the while loop more than 5 times")
      

      【讨论】:

      • 谢谢,你能在我的代码中添加一个例外吗?
      • 我得到了'NameError: name 'flag' is not defined'。我将标志添加为全局,但仍然得到相同的按摩
      • 您能否添加一个异常来仅停止代码(我不想退出它)。谢谢
      • 我添加了一个示例来说明我的意思。我不能使用你自己的代码,因为你的脚本有变量,我不清楚它们是什么。