Programming Tutorials

goto in Python

By: Kareem in Python Tutorials on 2012-04-07  

Python does not have a goto statement like some other programming languages. The use of goto can make code harder to understand and modify, and can lead to problems such as infinite loops.

However, Python provides alternatives to the goto statement for most use cases. For example, to break out of nested loops, you can use the break statement with a label to indicate which loop to break out of:

for i in range(10):
    for j in range(10):
        if i * j > 50:
            break outer
    print(i, j)

outer:
print("Done")

In this example, the break statement is used with the label outer to break out of both loops when i * j > 50. The program then continues execution after the outer: label.

Another alternative to the goto statement is to use functions or loops to structure your code in a more understandable way. By using functions, you can break up your code into smaller, more manageable chunks, and by using loops you can repeat code blocks without the need for a goto statement.

You can also use exceptions to provide a 'structured goto' that even works across function calls. Many feel that exceptions can conveniently emulate all reasonable uses of the 'go' or 'goto' constructs of C, Fortran, and other languages. For example:

class label: pass  # declare a label 
try: 
         ... 
         if (condition): raise label()  # goto label 
         ... 
    except label:  # where to goto 
         pass 
    ... 

This doesn't allow you to jump into the middle of a loop, but that's usually considered an abuse of goto anyway. Use sparingly.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)