Goto Statement in Python

A crucial piece of syntax or code in Python is the goto statement, which allows the user to skip a specific number of statements or a block of code inside the program body. Technically speaking, it performs an unconditional jump, within the context of the function that is being compiled, from the goto statement to the destination location. Get started with Python by understanding the fundamental OOPs concepts in Python. In this article, you will understand how the goto statement works in Python and gain expertise with coding skills.

Installation

pip install goto-statement

Example

from goto import with_goto

@with_goto

def range(start, stop):

i = start

result = []

label .begin

     if i == stop:

         goto .end

result.append(i)

     i += 1

     goto .begin

label .end

     return result

What is A Goto Statement?

A goto statement is a syntax or a segment of code that allows for an unconditional leap from the goto statement to a destination statement marked in the contents of the same function. Put simply, you must use the goto statement if you wish the program to skip a specific number of functions in between.

While most programmers use goto statements very frequently, using one for auditing reasons may occasionally be discouraged due to the difficulty of tracking the program flow when a goto statement is present. The goto statement would have neatly hopped several parts of the function, making it harder to find the precise destination if the programmer has to modify the program’s contents. Explore the top 5 IDEs for the Python programming language and execute your sample programs.

Syntax – 1

goto label;

……

label:

Syntax – 2

label:

goto label;

The label in the example above can be changed to any text you choose, except the word “go.” It can also be placed anywhere in the program, either above or below the go statement.

Note: Originally published as a joke on April 1st, 2004, the goto phrase quickly gained popularity among programmers worldwide. 

Sample Programs to Practice:

Fibonacci Series in Python | Palindrome Program in Python 

Goto Statements and Its Iterations

Comefrom is another Python code that functions in the same way as a goto statement. In Python, the ‘comefrom’ and ‘goto’ statements both increase program flexibility by providing accessibility to control flow idioms that were previously unattainable and enabling one to regulate program flow processes. Check out Jump Statements in Python

To utilize the ‘comefrom’ and goto statements in Python, one must import them from the main library first. To accomplish this, enter the code listed below. 

from goto import goto, comefrom, label

You can conveniently use these two functions throughout your program once the libraries have been imported. In Python, a goto statement effectively tells the interpreter to run the next line of code directly, rather than the one that is currently running. In the “label” section, you must indicate the specific line of code that you want the interpreter to run at this particular time. The label tag should be noted for its primarily random and arbitrary Python identifiers, which are prefixed with a single dot.

Example: label.myLabel

Comefrom

The comefrom statement in Python is essentially the goto statement’s reverse. The simplest way to understand its role for the interpreter would be to think of it as the following: “Whenever label X is reached, jump to here instead.”

# …code 1…

label .somewhere

# …code 2…

comefrom .somewhere

Code 2 in the statement mentioned above won’t be run. The interpreter will immediately jump to the following line that comes from “somewhere” when it encounters the line ‘label.somewhere’.

The fact that the comefrom statement is almost exclusively used as a programming debugging tool is another crucial feature to consider. 

It is generally not advised to utilize it for independent programming operations, as it can occasionally provide results that are both inconvenient and harmful. The Goto statement is one of the top 55 Python interview questions and answers in 2024.

Computed Goto Statement

The calculated goto statement is one of the most often used goto statement variants in Python, utilized by the majority of programmers. You refer to the Python index in this code at the outset and then use a hashtag to refer to it later on. Explore the top 10 frameworks in Python.

Unlike the previous example, the value of x in the above statement shouldn’t have the prefix dot.

Example

i = calculateLabelName()

Goto *i

Restrictions within the Goto statement

Python has a variety of limits on the comefrom and goto statements, just as other programming languages and platforms do. The limitations are as follows:

Programmers can’t switch between modules or functions simultaneously using both statements.

Jumping to the end of a loop or the ultimate clause is not always possible. Both of these statements are useless because the exception line was never detected in the first place. Discover the role of Python in artificial intelligence and enhance your fundamental skills for a better IT career. 

Example

from goto import goto, label

for x in range(1, 10):

for y in range(1, 20):

for z in range(1, 30):

print x,y,z

if z == 3:

goto .end

label .end

print “Finished”

The example mentioned above can be used to escape any loop, no matter how deeply nested.

Example: Cleaning after task failure

from goto import goto, label

def settingUp():

print “settingUp”

def doPrimaryTask():

print 0;

return True

def doSecondaryTask():

print 1;

return True

def doThirdTask():

print 2;

return False # It pretends to fail.

def doFourthTask():

print 3;

return True

def cleanUp():

print “cleanUp”

def bigFunction3():

settingUp()

if not doPrimaryTask():

goto .cleanup

if not doSecondaryTask():

goto .cleanup

if not doThirdTask():

goto .cleanup

if not doFourthTask():

goto .cleanup

label .cleanup

cleanUp()

bigFunction3()

print “bigFunction3 done”

For this reason, Python’s goto statement is a highly helpful command that may be used for debugging as well as auditing. Using a go-to statement often produces quite spectacular results, even if they are not used often in regular programming. We are unveiling the reason behind the bright future of Python here.

Example: Miscellaneous

Example 1: Using a computed goto

from goto import goto, label

label .getinput

i = raw_input(“Enter either ‘a’, ‘b’ or ‘c’, or any other letter to quit: “)

if i in (‘a’, ‘b’, ‘c’):

goto *i

else:

goto .quit

label .a

print “You typed ‘a'”

goto .getinput

label .b

print “You typed ‘b'”

goto .getinput

label .c

print “You typed ‘c'”

goto .getinput

label .quit

print “Finished\n”

Example 2: Restarting a loop:

from goto import goto, label

label .start

for i in range(1, 5):

     print i

if i == 3:

try:

    output = message

    except NameError:

print “Oops!  Start again please.”

message = “Hello world”

goto .start

print output, “\n”

Example 3: When a label goes missing

from goto import goto, label

label .isreal

goto .notreal      

#raises a MissingLabelError exception.

Learn more about goto statements and other crucial concepts of Python with hands-on exposure through our Python training in Chennai at SLA.