Working around a lack of 'goto' in python

Peter Otten __peter__ at web.de
Sat Mar 6 13:48:15 EST 2004


Brett wrote:

> Two areas where I've found 'goto' two be useful in other languages are in
> (untested examples in C++)
> 
> (1) deeply nested loops

class BeamMeUpScotty(Exception):
    pass

try:
    for i in range(10):
        for k in range(10):
            for n in range(10):
                if i == k == n == 2:
                    raise BeamMeUpScotty
except BeamMeUpScotty:
    pass

print (i, k, n)

Ok, I'm only kidding, here's the real thing:

def beamMeUp():
    for i in range(10):
        for k in range(10):
            for n in range(10):
                if i == k == n == 2:
                    return i, k, n

print beamMeUp()

> and (2) repeating a while or for loop from the beginning:
> 
> BEGIN:
> for (n=0; n < 20; ++n)
>     if (/* some test */) goto BEGIN;

while 1:
    for i in range(10):
        print i,
        if i == 5 and raw_input("restart?") != "no":
            break
    else:
        break


Can't remember having done that in my code, though. If the need arises I'd
probably go with the function approach again. To me goto seems much like a
speed hack that is fine in, say, the kernel code, but by no means in a
scripting language.

Peter




More information about the Python-list mailing list