def a():
g=1
def b():
global g
g=2
def c():
global g
g=3
c()
print("c", g) #3
b()
print("b", g) #1
a()
print("a", g) #3
The output is
c 3
b 1
a 3
I can’t understand why the value of g is 1 inside a() but 3 outside a()
If value of g is 3 in two places:
- after calling
c() - outside
a().
Why is it 1 inside a()?
>Solution :
When you do g=1 in a() it creates a new local variable to that function. When you do global g in b() and c() it makes g refer to the global variable (which doesn’t yet exist when running b). So c, b and the global scope all refer to the same g (which is 3 after running c) while a refers to its local g which never changed and is still 1.
Changing global to nonlocal will make both prints of c and b to print 3, but now will make a NameError for the last print as there is no g in the global scope.
Alternatively, adding global g to the start of a, will have all three prints print 3.