Working around a lack of 'goto' in python

David M. Cooke cookedm+news at physics.mcmaster.ca
Sun Mar 7 03:49:26 EST 2004


At some point, "Brett" <abc at def.net> wrote:

> Two areas where I've found 'goto' two be useful in other languages are in
> (untested examples in C++)
>
> (1) deeply nested loops
>
> for (k=0; k < 10; ++k)
> for (j=0; j < 10; ++j)
> for (i=0; i <10; ++i)
>     if (/* some test */) goto END;
>
> END: /* continue */;

If you're not doing anything between the loops, I like to use a
generator:

def iindices(klimit, jlimit, ilimit):
    for k in xrange(klimit):
        for j in xrange(jlimit):
            for i in xrange(ilimit):
                yield k, j, i

for k, j, i in iindices(klimit, jlimit, ilimit):
    if test_fails(k, j, i):
        break

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list