I am trying to better understanding scoping in python. I have the following toy example:
a = 1
print "in global: " + str(a)
def g():
a += 1
print "in g(): " + str(a)
def f():
a += 1
print "in f(): " + str(a)
g()
f()
I expected this to run and print out 1 then 2 then 2 again. However, instead I get en error:
UnboundLocalError: local variable 'a' referenced before assignment
I would have thought both g() and f() would pull a from the global scope. Incorrect?
UPDATED:
Thanks for the answers but what isn't clear is this: if I would like to just read the global variable a and assign it to a local variable that I create, also named a is that possible?
The reason I am doing this is I'm trying to figure out if g() inherits the scope of f() when it is called or the global scope where it is defined?