The purpose of the global statement is to
declare that a function or method intends to change the
value of a name from the global scope, that is, a name
from outside the function.
When Python reads the definition of a function, it checks
each name to see if that name's value may possibly be
changed anywhere in the function—that is, if the
name shows up on the left side of an assignment
statement, or as the induction variable in a for loop, or in any other context where the
name's value can be changed.
Such names are assumed to be local to the function unless
you override this behavior by declaring that name in a
global statement. Here is the general form:
globalname1,name2, ...
Some conversational examples may help make this clear.
Suppose you define a global variable x;
you can use that name inside a function.
>>> x = 5 >>> def show1(): ... print x ... >>> show1() 5
However, if you assign a value to x inside
the function, the name x is now local to
the function. It is said to shadow the global variable with the same
name, and any changes to the value associated with that
name inside the function will operate on a local copy,
and will not affect the value of the global variable
x.
>>> x = 5 >>> def show2(): ... x = 42 ... print x ... >>> show2() 42 >>> x 5
But if you actually do want to change the value of the global variable inside the function, just declare it global like this:
>>> x = 5 >>> def show3(): ... global x ... x = 42 ... print x ... >>> show3() 42 >>> x 42
Notice what happens in this case:
>>> x = 5 >>> def show4(): ... print x, "Before" ... x = 42 ... print x, "After" ... >>> show4() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in show4 UnboundLocalError: local variable 'x' referenced before assignment
Because the line “x = 42”
changes the value of x, and because it is
not declared as a global, execution fails because the
value of the local variable x is used
before that variable has had a value assigned to it.