Label and goto in python

Goto для Python

Добавляет ключевые слова ‘goto’ и ‘comefrom’ для Python.

Ключевые слова ‘goto’ и ‘comefrom’ добавляют гибкость механизмам управления потоком Python и позволяют программистам Python использовать многие общие идиомы потока управления, которые ранее им отказывали. Ниже приведены некоторые примеры.

Чтобы включить новые ключевые слова, добавьте следующую строку в начало вашего кода:

from goto import goto, comefrom, label

‘goto’ переводит выполнение программы непосредственно в другую строку кода. Целевая линия должна быть идентифицирована с помощью оператора ‘label’. Этикетки определяются с использованием ключевого слова ‘label’ и имеют имена, которые являются произвольными идентификаторами Python с префиксом одной точки, например:

Чтобы перейти к метке, используйте ключевое слово ‘goto’ следующим образом:

Вычисленный goto

Вы можете использовать вычисляемый goto, назначив имя метки переменной во время выполнения и ссылаясь на нее, используя следующую звездочку:

x = calculateLabelName() goto *x 

Значение «x» не должно содержать ведущую точку. См. Пример 5 ниже для полного примера.

‘comefrom’ — это противоположность ‘goto’. Это позволяет кусочку кода сказать «Когда бы ни была достигнута метка X, перейдите сюда». Например:

# . code 1. label .somewhere # . code 2. comefrom .somewhere 

Здесь «code 2» не будет выполняться — выполнение перейдет непосредственно из строки «label.somewhere» в строку «comefrom.somewhere». ‘comefrom’ обычно используется в качестве средства отладки — его использование в производственном коде не рекомендуется, поскольку оно может привести к неожиданному поведению.

Ограничения

Есть некоторые классы goto и comefrom, которые были бы неписаны, и, следовательно, есть некоторые ограничения на то, куда могут идти прыжки:

  • Никаких переходов между модулями или функциями
  • Никакой прыжок в середину цикла или предложение ‘final’
  • Нет прыжка на строку ‘except’ (потому что нет исключения)

Вот несколько примеров того, как можно использовать goto и comefrom:

# Example 1: Breaking out from a deeply nested loop: from goto import goto, label for i in range(1, 10): for j in range(1, 20): for k in range(1, 30): print i, j, k if k == 3: goto .end label .end print "Finished\n" # Example 2: Restarting a loop: from goto import goto, label label .start for i in range(1, 4): print i if i == 2: try: output = message except NameError: print "Oops - forgot to define 'message'! Start again." message = "Hello world" goto .start print output, "\n" # Example 3: Cleaning up after something fails: from goto import goto, label # Imagine that these are real worker functions. def setUp(): print "setUp" def doFirstTask(): print 1; return True def doSecondTask(): print 2; return True def doThirdTask(): print 3; return False # This one pretends to fail. def doFourthTask(): print 4; return True def cleanUp(): print "cleanUp" # This prints "setUp, 1, 2, 3, cleanUp" - no "4" because doThirdTask fails. def bigFunction1(): setUp() if not doFirstTask(): goto .cleanup if not doSecondTask(): goto .cleanup if not doThirdTask(): goto .cleanup if not doFourthTask(): goto .cleanup label .cleanup cleanUp() bigFunction1() print "bigFunction1 done\n" # Example 4: Using comefrom to let the cleanup code take control itself. from goto import comefrom, label def bigFunction2(): setUp() if not doFirstTask(): label .failed if not doSecondTask(): label .failed if not doThirdTask(): label .failed if not doFourthTask(): label .failed comefrom .failed cleanUp() bigFunction2() print "bigFunction2 done\n" # Example 5: 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 6: What happens when a label is missing: from goto import goto, label label .real goto .unreal # Raises a MissingLabelError exception. 

Этот модуль выпущен под лицензией Python Software Foundation, который можно найти по адресу http://www.python.org/ Для этого требуется Python 2.3 или новее.

Версия 1.0, выпущенная 1 апреля 2004 года. Скачайте здесь.

Источник

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 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

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

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

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.

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

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

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.

Источник

Читайте также:  What is algorithm in javascript
Оцените статью