Breaking out of nested loops

Peter Hansen peter at engcorp.com
Sat Jan 12 11:51:02 EST 2002


Ulf Magnusson wrote:
> 
> I guess you mean something like this
> ******************
> for i in ...:
>     for j in ....:
>          if some_condition:
>                 magic_break
> code continues here...
> ******************
> 
> There are not supposed to be such a magical break, to my knowledge no
> other language support this either. 

Sure they do.  'goto', probably among others.

> It kind of breaks the good behaviour you
> expect from a imparative programming language.

That much is true.

> The best solution is to set a flag inside the inner for loop and check for
> that the first thing in the outer for loop. 

You have to check that flag in each loop or you won't get yourself
out to the outer loop to have it checked.  That tends to make the
code somewhat unreadable when you have more than two nested loops.
One could argue that code with three nested loops already smells
a bit and should be refactored, but that's another story.

> Exceptions should only be used for real exceptions when something 
> is wrong, not to change the flow of the program.

The word "exception" simply refers to something other than the
normal case.  There's really nothing wrong with using it for
*exceptional* conditions, which obviously is the case with most
magic_breaks that get you out of a deeply nested loop.  There
are sometimes concerns with performance (using exceptions can
be much slower than simpler things in some languages) but 
generally I think this is probably the best way.

> But this is of course my humble opinion
> 
> Do I make any sence?

This is just _my_ humble opinion, but I think we both make sense... :)

-Peter



More information about the Python-list mailing list