The nonlocal statement in Python
There are cases when there is a variable in an outer function that needs to be accessed in an inner function. Let's declare a variable i in the function outer. With respect to the inner function, this variable will be external (global variables are those declared ONLY in the outer code). And let's define the function inner to add one to i:
def outer():
i = 0
def inner():
i += 1 # [4, 9, 25]
inner()
return i
However, for inner, the variable i is local, Python considers it undeclared and throws an error accordingly. Previously, this error was fixed by using the global statement. However, here i is an outer variable, so nonlocal should be used. It takes the listed variable names into the nearest scope, excluding the global one, i.e. i inside inner will be taken with the variable declared above the given function:
def outer():
i = 0
def inner():
nonlocal i
i += 1
inner()
return i
print(outer()) # 1
In the following code, some programmer made a mistake:
num = 10
def outer():
num = 5
def inner():
num -= 2
inner()
return num
print(outer())
What's wrong with this code? Find and fix the code author's mistake.
In the following code, some programmer made a mistake:
num = 3
def outer():
num += 1
tst = num
def inner():
tst = tst ** 3
inner()
return tst
print(outer())
What's wrong with this code? Find and fix the code author's mistake.