The trick to understanding this is that when you assign a variable using =, you also declare it a local variable. Therefore, instead of changing the value of the global variable a, setA (value) actually sets the local variable (which, as it turns out, is called a) into the value passed to.
This becomes more obvious if you try to print the value of a at the beginning of setA (value) as follows:
def setA(value): print "Before assignment, a is %d" % (a) a = value print "Inside setA, a is now %d" % (a)
If you try to run this Python, you will get a useful error:
Traceback (most recent call last):
File "scopeTest.py", line 14, in
setA (42)
File "scopeTest.py", line 7, in setA
print "Before assignment, a is% d"% (a)
UnboundLocalError: local variable 'a' referenced before assignment
This tells us that Python decided that the setA (value) function has a local variable called a, which you change when you assign it a function. If you do not assign a to a function (as with printA ()), then Python uses the global variable A.
To mark a variable as global, you need to use the global keyword in Python, in the area in which you want to use the global variable. In this case, it is the setA (value) function. Thus, the script becomes:
a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): global a a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA()
This one-line addition tells Python that when you use the a variable in the setA (value) function, you are talking about a global variable, not a local variable.