Python uses fairly typical variable scoping. Non-local variables are visible within a function.
You only need global keyword if you want to assign to a variable within global scope.
Also you have to note the difference between global and outer scope. Consider implications:
x = 'global'
def f():
x = 'local in f'
def g():
global x
x = 'assigned in g'
g()
print x
Upon execution of f() above code will print local in f, while x in global scope is set to 'assigned in g'.
As of Python 3, there is also nonlocal keyword, which allows you assigning to variable from outer scope.
x = 'global'
def f():
x = 'local in f'
def g():
nonlocal x
x = 'assigned in g'
return g
print(x)
Upon execution of f() above code will print 'assigned in g(which is the value ofxin local scope off()), while value ofx` in global scope remains untouched.
It's also worth to note, that Python uses lexical (static) scoping, thus following code does not modify the x in the global scope:
x = 'global'
def f():
x = 'local in f'
def g():
nonlocal x
x = 'assigned in g'
return g
g = f()
g()