In the example below we have a variable c
defined outside of any other function. In foo
we also declare a c
, increment it, and print it out. You can see that repeatedly calling foo()
will yield the same result over and over again, because the c
in foo
is local in scope to the function.
In bar
, however, the keyword global
is added before c
. Now the variable c
references any variable c
defined in the global scope (ie. our c = 1
instance defined before the functions). Calling bar
repeatedly updates the global c
instead of one scoped locally.
>>> c = 1
>>> def foo():
... c = 0
... c += 1
... print c
...
>>> def bar():
... global c
... c += 1
... print c
...
>>> foo()
1
>>> foo()
1
>>> foo()
1
>>> bar()
2
>>> bar()
3