How to break out of two nested for loops?

Alex Martelli aleax at aleax.it
Tue Jan 22 04:14:11 EST 2002


"Dale Strickland-Clark" <dale at riverhall.NOTHANKS.co.uk> wrote in message
news:shfp4uk9mhavveieacp0q2vjvuahn5dif6 at 4ax.com...
> Tom Jenkins <tjenkins at devis.com> wrote:
>
> >
> >well an easy way to break out of n loops is using an exception.
>
> This solution keeps cropping up but, IMHO, using an *exception* for
> something that isn't an exception is just as obscure, misleading and
> awkward as a goto.

In some languages, maybe, where 'exceptions' stick close to their
name's root, by only being geared to represent 'exceptional'
conditions.  In Python, exceptions are routinely used to signal
conditions that are anything BUT exceptional, such as a sequence
or iterator being finished in a for-loop (up to 2.1, exception
IndexError was used; in 2.2, StopIteration instead).


> So far, I have found that I can always code around the need to break
> out of nested loops without nasty constructs, exceptions or flags by
> using functions, classes or the 'else' clause.

I'll agree on this one -- with 2.2, and thus nested_scopes,
it's basically painless to use a local function, and 'return'.

However, I've found it useful (rarely, I'll admit) to use
exceptions to break out of deeply-nested *recursion*.


Alex






More information about the Python-list mailing list