Menu

Local and Global Variables

The global statement

The global statement tells Python that a name used inside a sub program means the single shared global variable, not a new local one. You need one in any sub program that assigns a new value to a global variable.

Writing the statement

Put it at the start of the sub program body, naming the variable it is about.

fuel = 40

def refuel():
    global fuel
    fuel = fuel + 15

refuel()
print(fuel)

Output:

55

Because of global fuel, the assignment inside refuel changes the one global fuel. The new value is still there after the sub program ends, so the main program prints the updated total.

The statement does not give the variable a value — the global already exists, created in the main program. It only says which variable the name refers to here. The line also affects nothing outside the sub program it is written in, so every sub program that assigns to fuel needs its own global line. A sub program that only reads the value needs no statement at all, because Python falls back to the global when there is no local of that name.

Without the statement

Python treats any name assigned inside a sub program as a new local variable. Assigning to it without a global statement therefore creates a separate local with that name, and the global keeps its original value — printing in the main program afterwards shows the value from before the call.

Sub program containsWhat the assignment does
global fuelChanges the shared global; the new value stays after the sub program ends
No global statementCreates a new local variable; the global is unchanged

Reading the name too early

Python decides what a name means by looking at the whole sub program, not just the line it sits on. If the sub program reads the name before the line that assigns to it, and there is no global statement, the program stops with an error: the name is a local variable that has not yet been given a value.

tickets = 12

def print_tickets():
    print(tickets)
    tickets = 0

print_tickets()

Output:

UnboundLocalError: cannot access local variable 'tickets' where it is not associated with a value (line 4)

Practise this