How to use goto statement
goto for Python
Adds the 'goto' and 'comefrom' keywords to Python.
The 'goto' and 'comefrom' keywords add flexibility to Python's control flow mechanisms, and allow Python programmers to use many common control flow idioms that were previously denied to them. Some examples are given below.
'goto' jumps the program execution directly to another line of code. The target line must be identified using a 'label' statement. Labels are defined using the 'label' keyword, and have names which are arbitrary Python identifiers prefixed with a single dot, like this:
You can use a computed goto by assigning the name of the label to a variable at runtime and referencing it using an asterisk like this:
The value of 'x' should not include the leading dot. See Example 5 below for a full example.
'comefrom' is the opposite of 'goto'. It allows a piece of code to say "Whenever label X is
reached, jump to here instead." For example:
Here, "code 2" will not run - execution will jump directly from the "label .somewhere" line to the "comefrom .somewhere" line. 'comefrom' is typically used as a debugging aid - its use in production code is discouraged since it can lead to surprising behaviour.
There are some classes of goto and comefrom which would be unpythonic, and hence there are some restrictions on where jumps can go:
- No jumping between modules or functions
- No jumping into the middle of a loop or a 'finally' clause
- No jumping onto an 'except' line (because there is no exception)
Here are some examples of how goto and comefrom can be used:
This module is released under the Python Software Foundation license, which can be found at http://www.python.org/ It requires Python 2.3 or later.
Version 1.0, released 1st April 2004. Download here .Source: entrian.com