Local and Global Variables
A local variable is a variable that belongs to one sub program. It is created inside that sub program, either by an assignment in its body or by being named in its parameter list. It can be used anywhere inside its own sub program, but nowhere else. In Python, that means a name first assigned inside the indented body of a def block, or listed in the brackets.
A local variable only exists while its sub program is executing. Once that sub program finishes, the variable is gone. It does not keep its value between calls: each call starts again with a fresh variable. If a sub program finishes with a local variable holding 7, the next call does not begin with 7 — the old variable has gone, so the sub program must create it again before it can be used again.
The main program cannot use it, and neither can any other sub program. Trying to use it outside its own sub program is an error, and the program stops rather than carrying on with a missing value. A parameter is local in the same way: it belongs to that one sub program and cannot be reached from outside. In the program below, cup_size belongs to make_smoothie, so the last line has no such variable to find.
def make_smoothie(fruit):
cup_size = "large"
print(fruit, "smoothie in a", cup_size, "cup")
make_smoothie("mango")
print(cup_size)Output:
mango smoothie in a large cup
NameError: name 'cup_size' is not defined (line 6)
Two different sub programs may each contain a local variable with the same name. These are completely separate variables held in separate areas of memory, so changing one has no effect at all on the other, even though the code in the two sub programs looks similar. Here, each sub program has its own local badge.
def make_badge(first_name):
badge = "Visitor: " + first_name
print(badge)
def make_ticket(last_name):
badge = "Ticket: " + last_name
print(badge)
make_badge("Zara")
make_ticket("Okafor")Output:
Visitor: Zara
Ticket: Okafor OCR GCSE Computer Science · Local and Global Variables