In this blog, we will discuss about the goto statement in python, but before that,
Note that we will be using loops, functions to solve this specific problem. To grab great insights of these topics and more along with its various applications and real-time projects, you can enroll in Python Online Training at FITA at an affordable price, which includes certification, support with career guidance assistance.
The goto statement appeared first on April’s Fool Day, 2004 as a joke for python, but programmers across the earth took it seriously and commenced developing it.
A goto statement is a piece of code or syntax that can jump from the goto statement to a labeled statement which is marked as end within the same function. If I elucidate this in layman terms, let’s say, you would like your program to skip some specific number of functions, during this case, a goto statement can be used between your program.
Although python supports goto statements, it is highly recommended not to use it as python is a highly structured language.
Syntax for goto statement in python.
goto <label> … <label>: … |
The label can be replaced with any other word
Iterations in goto statement
Another statement that works like goto is comefrom.
It is important that you use both the statements goto and comefrom to make jumps. So import them from the goto module.
from goto import label,goto,comefrom |
comefrom
The comefrom statement is opposite to goto statement.It’s function is to make the interpreter jump to the label instead of following the structure.
Here is its syntax
label .position … comefrom .position |
In the above example, the code after label .position will not be executed, and instead it directly jumps to a comfrom statement.
Now let’s write a program to implement a goto statement..
from goto import label,goto for i in range(1, 4): for j in range(1, 4): for k in range(1, 4): print(j,i*k,k) if k == 3: goto .end label .end print(“did a break from a nested for loop”) |
Equivalent Of goto In Python
You can use break,continue,pass or custom flags or functions instead of using goto and keep your program structured.Let’s write the above program without a goto statement.
def goto(): for i in range(1, 4): for j in range(1, 4): for k in range(1, 4): print(j,i*k,k) if k == 3: return print(“did a break from a nested for loop”) |
To get in-depth knowledge of Python along with its various applications, you can enroll for Python Training in Chennai or Python Training in Bangalore with certification, support and career guidance.