The equivalent of a GOTO in python

Calder Hutchins picture Calder Hutchins · Sep 18, 2013 · Viewed 375k times · Source

I am self teaching myself python 2.7. I have some experience in using BATCH, which has a GOTO statement. How do I do that in python? For example, suppose I want to jump from line 5 to line 18.

I realize there have been previous questions regarding this topic, but I have not found them sufficiently informative or, are too high level in python for my current understanding.

Answer

Tim Peters picture Tim Peters · Sep 18, 2013

Forgive me - I couldn't resist ;-)

def goto(linenum):
    global line
    line = linenum

line = 1
while True:
    if line == 1:
        response = raw_input("yes or no? ")
        if response == "yes":
            goto(2)
        elif response == "no":
            goto(3)
        else:
            goto(100)
    elif line == 2:
        print "Thank you for the yes!"
        goto(20)
    elif line == 3:
        print "Thank you for the no!"
        goto(20)
    elif line == 20:
        break
    elif line == 100:
        print "You're annoying me - answer the question!"
        goto(1)