Global Variables

Accessing Global Variables from within Local Scopes

A variable defined in the global scope is accessible from anywhere within your program, even from within local scopes. Let’s see an example of this.

def square_a():
    return a**2

#print(square_a())

a = 16

print(square_a())

a = 9

print(square_a())
256
81

Whenever a variable is referenced from within a local scope, Python will search that local scope for a variable with that name. If none is found, then it will search for the variable within the global scope. If no variable with that name is found in the global scope, then an error will be generated.

There are occasions when it is helpful to have a function access a global variable, but before doing so, you should always ask yourself if it would make more sense to simply define your function so that it can accept the global value as an argument.

def raise_to_a(x):
    return x**a

a = 3
print(raise_to_a(2))
print(raise_to_a(3))
print(raise_to_a(4))
8
27
64
def raise_to_power(x, power):
    return x**power

a = 3
print(raise_to_power(2, a))
print(raise_to_power(3, a))
print(raise_to_power(4, a))
8
27
64

Altering Global Variables from Within a Local Scope

Assume that we have a variable named my_var in the global scope, but do not currently have a variable with that name in body of a certain function.

  • If we reference my_var from within the function, in an expression like temp = my_var * 2, for example, then the value of my_var will be pulled from the global scope.

  • If we include in our function a line such as my_var = 2, then this will create a new local variable named my_var, masking the global variable with the same name. The value of my_var in the global scope will be unchanged.

def setAto50():
    a = 50
    return a

a = 37
print(a)
print(setAto50())
print(a)
37
50
37

But what if we do wish to change the value of a global variable from within a local scope? We can provide a function with permission to alter global variables using the global keyword. If we would like for a function to have write permission for a global variable, then at the beginning of the function, we can include a line containing the keyword global followed by the name of the variable.

def setAto50():
    global a 
    a = 50
    return a

a = 37
print(a)
print(setAto50())
print(a)
37
50
50