Is there a label/goto in Python?


Is there a goto or any equivalent in Python to be able to jump to a specific line of code?

Answer rating: 143

No, Python does not support labels and goto, if that is what you"re after. It"s a (highly) structured programming language.

Answer rating: 78

I recently wrote a function decorator that enables goto in Python, just like that:

from goto import with_goto

def range(start, stop):
    i = start
    result = []

    label .begin
    if i == stop:
        goto .end

    i += 1
    goto .begin

    label .end
    return result

I"m not sure why one would like to do something like that though. That said, I"m not too serious about it. But I"d like to point out that this kind of meta programming is actual possible in Python, at least in CPython and PyPy, and not only by misusing the debugger API as that other guy did. You have to mess with the bytecode though.

Get Solution for free from DataCamp guru