There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
How exactly does the nonlocal statement work?
Why does var2 exist in both the function2 local scope and in the function1 local scope? I would have expected var2 to only exist in function1’s local scope but not in function2’s local scope.
Furthermore, I noticed that the variable is both accessible and modifiable in both function1’s scope and in function2’s scope.
I made the following adjustments to the code to further investigate:
# Outer function
def function1():
global var1
var1 = 1
var2 = 2
# Inner function
def function2():
nonlocal var2
global var3
var2 += 1
var3 = 3
print(globals())
print(locals())
# Call inner function
function2()
print ('\n') #added line
print(locals()) #added line
var2 += 4 #added line
print(locals()) #added line
# Call outer function
function1()
Hi!
I have the same question! So I am looking forward to hearing an answer from some expert.
I also tried to see how “var2” stored in memory. After using “nonlocal” its id changes and it starts to exist in both local and enclosing namespaces with the same id.
# Outer function
def function1():
global var1
var1 = 1
var2 = 2
# Inner function
print("---ID of var2 in func1---")
print(id(var2))
def function2():
nonlocal var2
global var3
var2 += 1
var3 = 3
print("---ID of var2 in func2---")
print(id(var2))
print(globals())
print(locals())
# Call inner function
function2()
print("---ID of var2 in func1 after func2 execution---")
print(id(var2))
print(locals())
# Call outer function
function1()