Notes
A variable that is declared outside a function definition is a global variable. Global variables are accessible inside and outside of functions.
A variable that is declared inside a function definition is local. Local variables are only accessible inside the function.
Reading: http://www-inst.eecs.berkeley.edu/~selfpace/cs9honline/Q2/scope.html
Accessing a Global Variable inside a Function
x = 3 #since this x is declared outside a function, it is a global variable
def show_x():
print(x) #x is not declared in the function show_x(), however it can still be accessed because x is declared as a global variable
show_x()
Cannot Access a Local Variable from Outside of a Function
def setvalue_x():
x = 3 #x is local to the function setvalue_x and it is set to equal 3.
setvalue_x()
print(x) #there is an error accessing the variable x; even we called the setvalue_x to set the value of x to 3. However code outside of the function cannot access the value of a local variable
Global and Local Variables
x = 3 #x is declared as a global variable. It is set to be 3
def setvalue_x():
x = 5 #x is declared as a local variable inside the function setvalue_x. Although it has the same name as the variable outside of the function, they are different variable.
print(x) #this statement will print the local variable x (which is 5)
setvalue_x() #output is 5
print(x) #this statement will print the global variable x (which is 3)
Declare a Global Variable Inside a Function
def setvalue_x():
global x #we declare x as a global variable
x = 5
setvalue_x()
print(x) #since x is a global variable, we can access it outside of the function, thus the output is 5.
The Same Global Variable Inside and Outside of a Function
x = 3 #x is declared as a global variable. It is set to be 3
def setvalue_x():
global x #we declare x as a global variable, it is the same variable x as the x outside of the function
x = 5 #the global variable x value has been override to be 5
setvalue_x()
print(x) #output is 5