0 votes
in Python by
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?

1 Answer

0 votes
by
Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:

void somefunc(int a)

{

    if (a == 1)

        goto label1;

    if (a == 2)

        goto label2;

    label1:

        ...

    label2:

        ...

}

Could be done in python like this:

def func1():

    ...

def func2():

    ...

funcmap = {1 : func1, 2 : func2}

def somefunc(a):

    funcmap[a]()  #Ugly!  But it works.

Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.
...