Breaking out of nested loop

Raymond Hettinger othello at javanet.com
Tue Feb 27 12:22:28 EST 2001


jcm wrote:

> Phlip <phlip_cpp at my-deja.com> 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
> loops:
>
>   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

Adding a feature like is begging for hard to find errors.
A factored out function with a return almost always does
the trick and does it clearly.  And if not, then the needed
functionality is provided by try, except, and raise.

Raymond




More information about the Python-list mailing list