Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Why is there no goto in Python?
Yes, there is no goto statement in Python. Let us first understand what is a goto in C Language. However, the usage of goto is also discouraged in C.
The goto statement in C programming provides an unconditional jump from the 'goto' to a labelled statement in the same function. Following is the syntax ?
goto label; .. . label: statement;
Example
Let us now see a C program for goto ?
#include <stdio.h> int main () { int a = 10; LOOP:do { if( a == 15) { /* skip the iteration */ a = a + 1; goto LOOP; } printf("a = %d\n", a); a++; }while( a < 20 ); return 0; }
Output
a = 10 a = 11 a = 12 a = 13 a = 14 a = 16 a = 17 a = 18 a = 19
NOTE ? The use of goto statement is highly discouraged in C language as well.
No GoTo in Python
In Python, there?s no need of goto since we can accomplish the same with if statements and or, and, and if-else expressions & loop with while and for statements, containing continue and break.
User-defined Exceptions
Use user-defined exceptions as an alternative ?
class goto1(Exception): pass class goto2(Exception): pass class goto3(Exception): pass def loop(): print('start') num = input() try: if num<=0: raise goto1 elif num<=2: raise goto2 elif num<=4: raise goto3 elif num<=6: raise goto1 else: print('end') return 0 except goto1 as e: print('goto1') loop() except goto2 as e: print('goto2') loop() except goto3 as e: print('goto3') loop()
Nested Methods
Example
Use nested methods as another alternative ?
def demo(): print("In the demo() function") def inline(): print("In") inline() demo()
Output
In In the demo() function
The goto-statement module
It is a function decorator to use goto in Python. Tested on Python 2.6 through 3.6 and PyPy. Install it using the pip ?
Note: Works till Python 3.6
pip install goto-statement
Let us see an example ?
# Python 3.6 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
