Is there a label or any equivalent implementation in Python?
No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.
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.
@ascobol:
Your best bet is to either enclose it in a function or use an exception. For the function:
def loopfunc():
while 1:
while 1:
if condition:
return
For the exception:
try:
while 1:
while 1:
raise BreakoutException #Not a real exception, invent your own
except BreakoutException:
pass
Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)
To answer the @ascobol
's question using @bobince
's suggestion from the comments:
for i in range(5000):
for j in range(3000):
if should_terminate_the_loop:
break
else:
continue # no break encountered
break
Though I never saw such a code in practice.