Menu

Global & Local Variables

Global Declaration

A global declaration lets a subprogram change a global variable. It is written with the keyword global followed by the variable name.

Reading a global variable

Inside a subprogram, you can read a global variable without any special statement: using its value in a calculation or a print() call is enough. If Python cannot find the name inside the subprogram, it looks outside it, so no declaration is needed.

Assigning to a global variable

Assigning a new value is different. If a subprogram assigns to a name that matches a global variable without a declaration, Python creates a new local variable with the same name, and the global variable keeps its original value.

The declaration tells Python that the name refers to the global variable, so the assignment updates that variable. It only affects the subprogram it is written in.

temperature = 18

def cool_room():
    temperature = 12
    return temperature

print(cool_room())
print(temperature)

Output:

12
18
temperature = 18

def cool_room():
    global temperature
    temperature = 12

cool_room()
print(temperature)

Output:

12

In the first program, cool_room() works on its own local temperature, so the global variable is untouched. Adding global temperature inside the subprogram in the second program points the assignment at the global variable, so its value changes.

Two rows. Without a declaration, cool_room() makes a new local temperature = 12 and the global stays 18. With global temperature, the assignment changes the global variable to 12.

Practise this