x = 0
def outer():
x = 1
def inner():
nonlocal x
x = 2
def vnat():
nonlocal x
x = 5
print('vnat:', x)
vnat()
print('inner:', x)
inner()
print('outer:', x)
outer()
print('global:', x)
Here is the result:
vnat: 5
inner: 5
outer: 5
global: 0
Why is def outer() taking the value of def vnat() (5)? And how can I specify def outer() with value of nonlocal x from def inner() [2]?
Output I need:
vnat: 5
inner: 5
outer: 2
global: 0
Whenever you specify
nonlocal xit will refer to the name of an enclosing scope. So in your example, you have the following nesting of scopes:So
vnatrefers to its enclosing scope'sx(which is the scope ofinner) which in turn refers to its enclosing scope'sx(which is the scope ofouter). For that reason, if you assign toxinvnatit will effectively assign toouter's namex.