Breaking out of nested loop

jcm jmarshal at
Tue Feb 27 11:32:17 EST 2001

Phlip <phlip_cpp at> wrote:
> Proclaimed Dan from the mountaintops:

>> How might one go about breaking out of a multi level loop?
>> For instance, the following code will go into an endless loop.
>> while(1):
>>     while(1):
>>         break


> Your best bet (just like in a language that has a 'goto') is 'return'.

> Otherwiset you can 'raise' (irritating style that reminds one of VB), or 
> you can add a flag to the 'while' conditions and reset it at the 'break' 
> point.

Something I wouldn't mind seeing added to Python is a generalization
of break/continue statement[s], allowing you to break out of multiple

  break_or_continue_stmt: 'break'
                        | 'continue'
                        | 'break' break_or_continue_stmt

So you can do something like:

  while a:  # loop A
     while b:  # loop B
        while c:  # loop C
           break break  # breaks loops C and B, bringing
                        # you back to the body of loop A

More information about the Python-list mailing list