Reputation: 275
Let's say I have code that looks like this:
def lab():
letter = prompt()
def experiment_1():
if letter == 1:
print("check")
#Would there be a way to quit the lab function right here?
def experiment_2():
if letter == 1:
print("check2")
experiment_1()
experiment_2()
lab()
Would there be a way for me to quit the lab function right after I print "check"? I tried putting return at the end of experiment_1
but that just seems to go right to the next function which is experiment_2
.
Upvotes: 11
Views: 6010
Reputation: 59654
The most obvious way is to raise an exception. It will allow you to get out from any depth. Define a custom exception and catch it at some outer level. For example:
class MyError(Exception):
pass
def _lab():
letter = prompt()
def experiment_1():
if letter == 1:
print("check")
raise MyError
def experiment_2():
if letter == 1:
print("check2")
experiment_1()
experiment_2()
def lab():
try:
return _lab()
except MyError:
return
lab()
This particular example is kind of ugly, but you should get the idea.
Upvotes: 13
Reputation: 489
You can put return
statement just in the place that you want to function ends. In you can returns any other thin would be return var1 var2
def lab():
letter = prompt()
def experiment_1():
if letter == 1:
print("check")
# Would there be a way to quit the lab function right here?
# you have to put return just here
return
def experiment_2():
if letter == 1:
print("check2")
experiment_1()
experiment_2()
lab()
Upvotes: -2
Reputation: 1942
As said in comments section, you can pass a flag to the outer function
def lab():
letter = prompt()
def experiment_1():
if letter == 1:
print("check")
return True
return False
def experiment_2():
if letter == 1:
print("check2")
if experiment_1():
return
experiment_2()
lab()
But you should improve your question because it sounds like you are trying to solve another problem. See: http://mywiki.wooledge.org/XyProblem
Upvotes: 1