How to break out of multiple loops?

后端 未结 30 3376
情书的邮戳
情书的邮戳 2020-11-21 05:48

Given the following code (that doesn\'t work):

while True:
    #snip: print out current state
    while True:
        ok = get_input(\"Is this ok? (y/n)\")
          


        
30条回答
  •  青春惊慌失措
    2020-11-21 06:23

    I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you really need to break out of nested loops, here's an interesting variant of the exception-raising approach that @S.Lott described. It uses Python's with statement to make the exception raising look a bit nicer. Define a new context manager (you only have to do this once) with:

    from contextlib import contextmanager
    @contextmanager
    def nested_break():
        class NestedBreakException(Exception):
            pass
        try:
            yield NestedBreakException
        except NestedBreakException:
            pass
    

    Now you can use this context manager as follows:

    with nested_break() as mylabel:
        while True:
            print "current state"
            while True:
                ok = raw_input("Is this ok? (y/n)")
                if ok == "y" or ok == "Y": raise mylabel
                if ok == "n" or ok == "N": break
            print "more processing"
    

    Advantages: (1) it's slightly cleaner (no explicit try-except block), and (2) you get a custom-built Exception subclass for each use of nested_break; no need to declare your own Exception subclass each time.

提交回复
热议问题