intmain(){inta=10;LOOP:do{if(a==15) {/*skiptheiteration*/a=a+1;gotoLOOP;}printf(&"/> intmain(){inta=10;LOOP:do{if(a==15) {/*skiptheiteration*/a=a+1;gotoLOOP;}printf(&">

Home >Backend Development >Python Tutorial >Why is there no goto statement in Python?

Why is there no goto statement in Python?

WBOY
WBOYforward
2023-08-30 21:49:151764browse

Why is there no goto statement in Python?

Yes, there is no goto statement in Python. Let’s first understand what goto is in C language. However, the use of goto is also discouraged in C.

The goto statement in C programming provides an unconditional jump from "goto" to a marked statement in the same function. The following is the syntax -

goto label;
..
.
label: statement;

Example

Now let’s look at the goto C program -

#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 statements is also discouraged in C language.

There is no GoTo in Python

In Python, goto is not needed as we can accomplish the same task using if statements and or, and, if-else expressions and loops (including continue and break) using while and for statements.

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 method

Example

Use nested methods as another option -

def demo():
   print("In the demo() function")
def inline():
   print("In")
inline()
demo()

Output

In
In the demo() function

goto statement module

It is a function decorator using goto in Python. Tested on Python 2.6 to 3.6 and PyPy. Install it using pip -

Note: Applicable to Python 3.6

pip install goto-statement

Let’s 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

The above is the detailed content of Why is there no goto statement in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more