Python – Global variables

In this post we will be going through the creation of global variables in Python. In simplistic terms these are variables the are global, this is as opposed to local variables which may only exist in a certain function.

See the snippet of code below. Here we have a variable named ‘Global_Variable’ which equals ‘1’. We have two functions the first is ‘Function1’ which sets the value of the ‘Global_Variable’ to ‘1008’. We also have ‘Function2’ which prints the ‘Global_Variable’.

Global_Variable = 1

def Function1():
    Global_Variable = 1008

def Function2():
    print (Global_Variable)

Function1()
Function2()

In the example above whilst running ‘Function2’ the script will output ‘1’ and NOT ‘1008’. This is because the change made in ‘Function1’ was local to that function and not to the variable declared in line 1.

Using the global keyword in Python we can change this and have ‘Function2’ print out the updated variable. Refer to the snippet of code below as an example. The code below will output the updated value of ‘1008’.

Global_Variable = 1

def Function1():
    global Global_Variable #Global keyword here
    Global_Variable = 1008

def Function2():
    print (Global_Variable)

Function1()
Function2()

Leave a Reply