When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function. That is, variable declarations are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in, starting from the point of definition of the variable.
If you want to assign to a variable defined outside the function, then you have to use the global statement. This is used to declare that the variable is global i.e. it is not local. It is impossible to assign to a variable defined outside a function without the global statement.
You can use the values of such variables defined outside the function (and there is no variable with the same name within the function). However, this is discouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is. Using the global statement makes it clear that the variable is defined in an outer block.
Example 7.4. Using the global statement
#!/usr/bin/python # Filename : func_global.py def func(): global x print 'x is', x x = 2 print 'Changed x to', x x = 50 func() print 'Value of x is', x
The global statement is used to declare that x is a global variable. Hence, when we assign to x inside the function, that change is reflected when we use the value of x in the outer block i.e. the main block in this case.
You can specify more than one global variable using the same global statement. For example, global x, y, z .