def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
Hi I am dealing with python class and faced with above example from the official documentation.
Output:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
The result of the first print after do_local
still prints "test spam" but can't figure out why while the second print gives "nonlocal spam".
What makes the difference?
My inference is, if I do_local() then it runs the do_local() and it changes the spam variable as "local spam" and it might have to work same with do_nonlocal() which results in "nonlocal spam". But it's not.
Why?