954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Python goto

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

Rete
Newbie Poster
23 posts since Jun 2005
Reputation Points: 10
Solved Threads: 1
 

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
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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.

scru
Posting Virtuoso
1,629 posts since Feb 2007
Reputation Points: 975
Solved Threads: 140
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You