The scope of a variable, is the region of the program in which it is accesible. Up until now, all the variables you have created have been accesible everywhere in your program, but variables defined and used within a function are different.
It is possible to have the same variable name for different variables. In terms of the box analogy, it is possible to have boxes with different contents, with the same label as long as Python can determine which should be used in that region of the Program. When Python sees a variable name it applies the ``LGB'' rule to determine which ``box to look in''.
It first looks in the "Local" list of names for the variable. This is
the variables defined within the function, e.g. x and y in
the addnumbers() example function in Section
3.11. However, if the name is not found it
then looks in the ``Global'' list, which is a list of variables
accesible from everywhere. If the name is not found there it then
resorts to the ``Built-in'' names (things like range() and
input).
Here is an illustrative example:
def addnumbers(x,y):
spam = "LOCAL SPAM!!" # Local definition
print "spam inside the function is:", spam
return x + y
spam = "GLOBAL SPAM!!"
print addnumbers(5,10) # Function called here
print "spam outside the function is:", spam
When the function is called, it does what our original
addnumbers() function did, i.e. returns the sum of the two
parameters. It also prints the contents of the variable spam.
This is defined locally, so Python does not bother to look in the
Global or Built-in lists (where it is defined differently).
When spam is printed again outside the function
addnumbers() the first spam Python finds is the Global
definition. Python cannot descend into the Local list of the function.
This may seem confusing, but it is done for a good reason. The crucial point to take away from this section is one important implication for the way you write your programs:
If you change a variable inside a function, and then inspect it (by printing it for example) outside the function that change will not be reflected:
>>> def addnumbers(x, y):
z = 50
sum = x + y
return sum
>>> z =3.14
>>> print addnumbers(10, 5)
15
>>> print z
3.14
If you really whant these changes to be reflected globally, then tell
Python so by making the variable, z in this case global.
>>> def addnumbers(x, y):
global z
z = 50
sum = x + y
return sum
>>> z =3.14
>>> print addnumbers(10, 5)
15
>>> print z
50
Note that making variables global can cause subtle problems and, if possible, should be avoided. As alluded to in the footnote in Section 3.11 you may find it better to pass the result back as a list.