Hi again, I just had a really quick question. Is there any kind of goto command in Python like there is in Java?

Recommended Answers

All 3 Replies

Python has no goto statement. In C as in Java a goto should only be used in special cases, like breaking out of a series of nested loops. Here is a Python workaround ...

# setting a binary flag will work, similar to a goto in C
loopsDone = False
print '-'*20
for x1 in range(3):
    if loopsDone:
        break
    print 'x1 =', x1,
    for x2 in range(3):
        if loopsDone:
            break
        print 'x2 =', x2,
        for x3 in range(3):
            print 'x3 =', x3
            if x3 == 1:
                loopsDone = True
                break  # flag helps to break out of all loops

An alternative is this

class LabelFoo(Exception):
    pass

print '-'*20
try:
    for x1 in range(3):
        print 'x1 =', x1,
        for x2 in range(3):
            print 'x2 =', x2,
            for x3 in range(3):
                print 'x3 =', x3
                if x3 == 1:
                    raise LabelFoo
except LabelFoo:
    pass

An alternative is this

class LabelFoo(Exception):
    pass

print '-'*20
try:
    for x1 in range(3):
        print 'x1 =', x1,
        for x2 in range(3):
            print 'x2 =', x2,
            for x3 in range(3):
                print 'x3 =', x3
                if x3 == 1:
                    raise LabelFoo
except LabelFoo:
    pass

Somewhere out there a unicorn just got mauled by a puppy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.