How to break out of multiple loops?

后端 未结 30 3246
情书的邮戳
情书的邮戳 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:24

    This isn't the prettiest way to do it, but in my opinion, it's the best way.

    def loop():
        while True:
        #snip: print out current state
            while True:
                ok = get_input("Is this ok? (y/n)")
                if ok == "y" or ok == "Y": return
                if ok == "n" or ok == "N": break
            #do more processing with menus and stuff
    

    I'm pretty sure you could work out something using recursion here as well, but I dunno if that's a good option for you.

    0 讨论(0)
  • 2020-11-21 06:24

    Since this question has become a standard question for breaking into a particular loop, I would like to give my answer with example using Exception.

    Although there exists no label named breaking of loop in multipally looped construct, we can make use of User-defined Exceptions to break into a particular loop of our choice. Consider the following example where let us print all numbers upto 4 digits in base-6 numbering system:

    class BreakLoop(Exception):
        def __init__(self, counter):
            Exception.__init__(self, 'Exception 1')
            self.counter = counter
    
    for counter1 in range(6):   # Make it 1000
        try:
            thousand = counter1 * 1000
            for counter2 in range(6):  # Make it 100
                try:
                    hundred = counter2 * 100
                    for counter3 in range(6): # Make it 10
                        try:
                            ten = counter3 * 10
                            for counter4 in range(6):
                                try:
                                    unit = counter4
                                    value = thousand + hundred + ten + unit
                                    if unit == 4 :
                                        raise BreakLoop(4) # Don't break from loop
                                    if ten == 30: 
                                        raise BreakLoop(3) # Break into loop 3
                                    if hundred == 500:
                                        raise BreakLoop(2) # Break into loop 2
                                    if thousand == 2000:
                                        raise BreakLoop(1) # Break into loop 1
    
                                    print('{:04d}'.format(value))
                                except BreakLoop as bl:
                                    if bl.counter != 4:
                                        raise bl
                        except BreakLoop as bl:
                            if bl.counter != 3:
                                raise bl
                except BreakLoop as bl:
                    if bl.counter != 2:
                        raise bl
        except BreakLoop as bl:
            pass
    

    When we print the output, we will never get any value whose unit place is with 4. In that case, we don't break from any loop as BreakLoop(4) is raised and caught in same loop. Similarly, whenever ten place is having 3, we break into third loop using BreakLoop(3). Whenever hundred place is having 5, we break into second loop using BreakLoop(2) and whenver the thousand place is having 2, we break into first loop using BreakLoop(1).

    In short, raise your Exception (in-built or user defined) in the inner loops, and catch it in the loop from where you want to resume your control to. If you want to break from all loops, catch the Exception outside all the loops. (I have not shown this case in example).

    0 讨论(0)
  • 2020-11-21 06:25

    Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:

    breaker = False #our mighty loop exiter!
    while True:
        while True:
            if conditionMet:
                #insert code here...
                breaker = True 
                break
        if breaker: # the interesting part!
            break   # <--- !
    

    If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!

    0 讨论(0)
  • 2020-11-21 06:25

    Hopefully this helps:

    x = True
    y = True
    while x == True:
        while y == True:
             ok = get_input("Is this ok? (y/n)") 
             if ok == "y" or ok == "Y":
                 x,y = False,False #breaks from both loops
             if ok == "n" or ok == "N": 
                 break #breaks from just one
    
    0 讨论(0)
  • 2020-11-21 06:26

    And why not to keep looping if two conditions are true? I think this is a more pythonic way:

    dejaVu = True
    
    while dejaVu:
        while True:
            ok = raw_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y" or ok == "n" or ok == "N":
                dejaVu = False
                break
    

    Isn't it?

    All the best.

    0 讨论(0)
  • 2020-11-21 06:26

    Another way of reducing your iteration to a single-level loop would be via the use of generators as also specified in the python reference

    for i, j in ((i, j) for i in A for j in B):
        print(i , j)
        if (some_condition):
            break
    

    You could scale it up to any number of levels for the loop

    The downside is that you can no longer break only a single level. It's all or nothing.

    Another downside is that it doesn't work with a while loop. I originally wanted to post this answer on Python - `break` out of all loops but unfortunately that's closed as a duplicate of this one

    0 讨论(0)
提交回复
热议问题