Breaking out of nested loops
Peter Hansen
peter at engcorp.com
Sun Jan 13 12:31:36 EST 2002
Paul Sidorsky wrote:
>
> I tend to agree that this feature isn't really needed - the flag
> approach or isolate-into-a-function approach usually works for me.
> However, such a feature might be reasonable if the "strong" break is
> tied to to the loop itself rather than the break statement. For
> example, something like this:
>
> i = 1
> while i < 20:
> j = 1
> while trans j < 20:
> if i * j > 200:
> break # Quits both loops because of trans
> j += 1
> i += 1
>
> Here "trans" is a new keyword or directive that tells Python that a
> break in the loop is to be "transparent", i.e. that it will propagate
> down to the loop below.
Not very flexible though, as you can't have a break in the inner
loop break *only* out of the inner loop, and yet have another
break in the next-to-inner loop break out of that loop, and still
have your "trans" break manage to get out of all the loops.
That is, this won't work:
while #1
while trans #2
while trans #3
break (normally) to the middle while
break (trans-style) to outer loop
break normally (to outer loop)
> To me, the main advantages with this approach are:
>
> 1) 100% backwards compatible.
> 2) Explicit
I'm not sure it's very explicit, since you are affecting the
behaviour of *break* statements, yet applying the modifier
to the loop construct.
> 3) Maintainable
Not very maintainable if not readable. No other language that
I'm aware of has such a thing, and that makes it a somewhat
bizarre new concept that nobody would "get" at first.
More important that anything when considering a new syntax,
however, is the question do you *really* need it.
No! As you said, we don't.
More information about the Python-list
mailing list