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
.
A closure is an inner function that has access to the outer (enclosing) function's variables — scope chain.
If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.
A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With