Breaking out of nested loops

Ulf Magnusson ulf.magnusson at ubm-computing.com
Sat Jan 12 15:56:01 EST 2002


"Peter Hansen" <peter at engcorp.com> wrote in message
news:3C406976.B3819BB7 at engcorp.com...
> 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.

I actually thought about that before, but goto in an ameoba which
shouldn't exist in any programming language except assembler.
that of course also IMHO.
But the fact remains, it could be used to perform the wished behaviour,
which you pointed you.

> > 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... :)

Yes, I agree with you Peter, but I guess it is more a question of religion
than
what is right or wrong here.
I for one, am really restrictive using exceptions in non "failure"
situations
>
> -Peter

/U. Magnusson





More information about the Python-list mailing list