The equivalent of a GOTO in python [duplicate] The equivalent of a GOTO in python [duplicate] python python

The equivalent of a GOTO in python [duplicate]


Forgive me - I couldn't resist ;-)

def goto(linenum):    global line    line = linenumline = 1while 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)


Gotos are universally reviled in computer science and programming as they lead to very unstructured code.

Python (like almost every programming language today) supports structured programming which controls flow using if/then/else, loop and subroutines.

The key to thinking in a structured way is to understand how and why you are branching on code.

For example, lets pretend Python had a goto and corresponding label statement shudder. Look at the following code. In it if a number is greater than or equal to 0 we print if it

number = input()if number < 0: goto negativeif number % 2 == 0:   print "even"else:   print "odd"goto endlabel: negativeprint "negative"label: endprint "all done"

If we want to know when a piece of code is executed, we need to carefully traceback in the program, and examine how a label was arrived at - which is something that can't really be done.

For example, we can rewrite the above as:

number = input()goto checklabel: negativeprint "negative"goto endlabel: checkif number < 0: goto negativeif number % 2 == 0:   print "even"else:   print "odd"goto endlabel: endprint "all done"

Here, there are two possible ways to arrive at the "end", and we can't know which one was chosen. As programs get large this kind of problem gets worse and results in spaghetti code

In comparison, below is how you would write this program in Python:

number = input()if number >= 0:   if number % 2 == 0:       print "even"   else:       print "odd"else:   print "negative"print "all done"

I can look at a particular line of code, and know under what conditions it is met by tracing back the tree of if/then/else blocks it is in. For example, I know that the line print "odd" will be run when a ((number >= 0) == True) and ((number % 2 == 0) == False).


I entirely agree that goto is poor poor coding, but no one has actually answered the question. There is in fact a goto module for Python (though it was released as an April fool joke and is not recommended to be used, it does work).