How To Use goto/label In Python3?

How To Use Gotolabel In Python3

The goto statement is very popular in other programming languages like C, C++. The goto statement is the arrangement of code to jump from one part to another. We can skip some parts of the code using this goto statement. Certain functions from code can be skipped using these goto statements. There is no specific goto statement in Python. Instead of a goto statement, we can use different loops, functions, and conditional statements in Python. This method will provide the same functionality as the goto statement. Let’s see the details about how to use the goto statement in Python.

Syntax of Goto Statement in C/C++ Language

The goto statement is used in different programming languages like C/C++ to skip functions or some part of the code. Let’s see one example of a goto statement to understand the working.

#include <stdio.h>
int main() {
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (num % 2==0) {
        goto even;
    }
    else {
        goto odd;
    }

even:
    printf("The number is even.\n");
    goto end;

odd:
    printf("The number is odd.\n");
    goto end;

end:
    printf("Program execution completed.\n");

    return 0;
}

In this piece of code, first, we ask the user to enter the number (integer), %d is used as a format specifier. The next line of code contains the conditions to test the number and classify it under some group. For example, the odd or even. In the end, we are using the end: statement to finish the code. Let’s see the output of this code.

Goto Statement
Goto Statement

Here, we have provided 5 as an input integer. The result is an odd number which is correct.

Is There Any Goto Statement in Python?

The specific built-in goto statement is not available in Python. In Python language from the beginning goto statement is never included in built-in functions. Instead, we can use comefrom, goto, and label statements in Python. These statements have some restrictions, which we’ll discuss in the later part of this article. First, let’s understand what are goto, comefrom, and label statements in Python.

Goto, Comefrom, and Label Statements in Python

The goto and comefrom both statements work similarly. The label statement works with the goto statement in Python. The label statement contains the piece of code which is the destination. The other code which lies between the goto and label will be skipped. The label statement is executed in the comefrom statement first, and jumping to the comefrom statement helps to skip the piece of code.

Goto With Label Statement in Python 2. x version

To use the goto statement in Python we need to call ‘with_goto’ from the goto package. The ‘.label’ syntax is used with it. Python.2.x supports this type of statement. If you try to implement this using an updated version the code will throw an error. Otherwise, you can implement this code in any other smaller versions.

Comefrom With Label Statement in Python 2. x version

To use the goto statement in Python we need to call the ‘label’ statement first and then skip the piece of code to execute the next function under comefrom. debugging becomes easy due to comefrom statements in Python. These statements are also used in smaller versions of Python. This will also throw an error if we try to implement this code in Python 3. x.

Other Alternatives of ‘Goto’ Statements in Python3?

if, elif, and else Statement in Python?

The if, elif, and else statements can be used as the best alternatives to the goto statement in Python. The consecutive implementation of three statements helps to skip the piece of code. Let’s execute one example to understand the implementation of the ‘if, elif, else’ loops.

Percentage = int(input("Enter your age: "))
if Percentage < 90:
    print("You are not eligible in A class.")
elif Percentage == 90:
    print("You are eligible")
else:
    print("You are completely eligible")

In this example, based on percentage we are classifying students. According to the percentage, the students will be classified as they are eligible or not. The 2nd line of code uses the if statement, the 4th line uses the elif statement, and the 6th line contains the else statement. According to the conditions the students are distributed in different classes. Let’s see the result.

If Elif Else Statement
If Elif Else Statement

In the results, we can see the marks entered is around 94% so, the student is completely eligible for class A. The result is correct.

For Loop Instead of ‘goto’ Statement

For loop is also used as a good replacement for a goto statement. If we set for loop in a range of 1 and try to implement different blocks of codes according to the conditions, then we can control the flow of the code.

X = 10
for i in range(1):
    i=X
    print("Executing code block1")
    if X==10:
      break
    i=X
    i=i+1
    print("Executing code block2")
    if X>=11:
      break
print("outside the loop")

In this example, the for loop is used for setting the range of the code, and the if statement is used to set the conditions. We have provided one statement for each block and here we are trying to ignore the block2. Let’s see the result.

For Loop As Goto Statement
For Loop As Goto Statement

In the results, we can see the statements of block 1 and statements outside the loop are printed.

While Loop Instead of Goto Statement

In this method, we are using a while loop instead of a goto statement. The ‘While loop’ executes code until the condition is satisfied. Once the condition fails the loop terminates. So, we can control the flow of code and execution using condition. Let’s try this method.

X=10
while X<15:
    print("Executing Block1")
    X=X+1
    
print("Executing Outer Block")

In this example, we are printing a statement until the value of X is less than 15. Once the value reached to15, the loop will be terminated and the final statement will be printed.

While Loop Instead Of Goto Statement
While Loop Instead Of Goto Statement

Function Instead of Goto Statement

In this method, we are using a Function instead of a goto statement. This execution of function using the condition can control the flow of the code. The functions are called and executed until the condition is satisfied and then terminated. Using a function instead of a goto statement also helps control the code.

X=11
def my_function():
    X=11
    X=X+1
    print("Executing my_function here")
    
def main():
    while X>10:
        my_function()

main()

The function in this code is my_function which is used to print the statement. The X variable is also declared inside the function so, the condition can be checked using a while loop. Let’s execute the code to see the results.

Functions Instead Of Goto Statement
Functions Instead Of Goto Statement

In the output, the condition is satisfied so, the loop is iterating infinite times with the main() function.

Why Goto Statement is Excluded From Python3?

The goto statement is very convenient to control the flow and execution of the code. Python3 does not include the goto statement but, the smaller versions of Python support goto, comefrom, and label statements. The goto statement created a sort of confusion while executing the code that’s why the goto statement is excluded. Instead of the goto statement the Python language provides a vast variety of options like if, elif, else, for loop, while loop, and functions to control the flow of code.

Summary

In this article, the details related to the goto statement are given. Python does not support the direct use of the goto statement. Instead of goto statements, we can use the if, elif, else, for loop, while loop, and functions. All the methods are explained with the example. Hope you will enjoy this article.

References

You can read stack overflow for reference.