flow control and nested loops

Bearophile bearophileHUGS at lycos.com
Sat Sep 26 22:17:58 CEST 2009


Raymond Hettinger:

> Another approach for exiting multiple levels of loops is wrap the
> inner calls in a function and return from them when needed:
>
>    def f(x):
>        for y in y:
>            for z in Z:
>                if test1(x,y,z):
>                    return
>                frobnicate(x,y,z)
>
>    for x in X:
>       f(x)

That's usual the solution I use for this problem, it's a little rough
and it has some performance cost, but it's readable and simple.

In PHP break and continue accept an optional numeric value (default is
1, 0 is of course ignored) "which tells it how many nested enclosing
structures are to be broken out of.":
http://us2.php.net/manual/en/control-structures.break.php
http://us2.php.net/manual/en/control-structures.continue.php
That PHP design gives me shivers, it's horrid, bug-prone and fragile:

for x in X:
    for y in Y:
        for z in Z:
            if test1(x, y, z):
                continue 3
            if test2(x, y, z):
                continue 2
            frobnicate(x, y, z)
        glortz(x, y)
    splat(x)


A better solution is to add labels to Python (I hope this code is
equivalent to the original Perl one), that can optionally be used by
"continue" and "break". This solution design is also used by D:

label OUTER:
for x in X:
    label INNER:
    for y in Y:
        for z in Z:
            if test1(x, y, z):
                continue OUTER
            if test2(x, y, z):
                continue INNER
            frobnicate(x, y, z)
        glortz(x, y)
    splat(x)

Bye,
bearophile



More information about the Python-list mailing list