I am self teaching myself python 2.7. I have some experience in using BATCH, which has a GOTO statement. How do I do that in python? For example, suppose I want to jump from line 5 to line 18.
I realize there have been previous questions regarding this topic, but I have not found them sufficiently informative or, are too high level in python for my current understanding.
Forgive me - I couldn't resist ;-)
def goto(linenum):
global line
line = linenum
line = 1
while True:
if line == 1:
response = raw_input("yes or no? ")
if response == "yes":
goto(2)
elif response == "no":
goto(3)
else:
goto(100)
elif line == 2:
print "Thank you for the yes!"
goto(20)
elif line == 3:
print "Thank you for the no!"
goto(20)
elif line == 20:
break
elif line == 100:
print "You're annoying me - answer the question!"
goto(1)
I entirely agree that goto
is poor poor coding, but no one has actually answered the question. There is in fact a goto module for Python (though it was released as an April fool joke and is not recommended to be used, it does work).
answer = None
while True:
answer = raw_input("Do you like pie?")
if answer in ("yes", "no"): break
print "That is not a yes or a no"
Would give you what you want with no goto statement.
There's no goto
instruction in the Python programming language. You'll have to write your code in a structured way... But really, why do you want to use a goto
? that's been considered harmful for decades, and any program you can think of can be written without using goto
.
Of course, there are some cases where an unconditional jump might be useful, but it's never mandatory, there will always exist a semantically equivalent, structured solution that doesn't need goto
.
Disclaimer: I have been exposed to a significant amount of F77
The modern equivalent of goto
(arguable, only my opinion, etc) is explicit exception handling:
Edited to highlight the code reuse better.
Pretend pseudocode in a fake python-like language with goto
:
def myfunc1(x)
if x == 0:
goto LABEL1
return 1/x
def myfunc2(z)
if z == 0:
goto LABEL1
return 1/z
myfunc1(0)
myfunc2(0)
:LABEL1
print 'Cannot divide by zero'.
Compared to python:
def myfunc1(x):
return 1/x
def myfunc2(y):
return 1/y
try:
myfunc1(0)
myfunc2(0)
except ZeroDivisionError:
print 'Cannot divide by zero'
Explicit named exceptions are a significantly better way to deal with non-linear conditional branching.
Source: Stackoverflow.com