Subprograms
A local variable belongs to the subprogram it is written in. It is created at the moment the subprogram is called and destroyed as soon as the subprogram returns. Its lifetime is just that one call, and its scope — the part of the program where it can be used — is that subprogram alone. These are two different things: lifetime is how long it exists, scope is where it can be seen.
Each call builds a fresh set of local variables, uses them, then throws them away. Calling the same subprogram twice gives two separate sets, so nothing is left over from the first call.
def ticketCost(adults, children):
adultCost = adults * 9
childCost = children * 5
total = adultCost + childCost
return total
cost = ticketCost(2, 3)
print(cost)Output:
33While ticketCost runs, its parameters adults and children and the local variables adultCost, childCost and total all exist. The instant it returns, all five stop existing, and only the returned value survives because the caller stored it in cost.
Parameters are local variables too. In the example, adults and children receive their values from the call, but they are not names the rest of the program can use. Because a local variable is private to its subprogram, the main program cannot read it after the call, and one subprogram cannot see another subprogram's locals at all. That is why two different subprograms can each have their own variable called total without interfering with each other.
If a value is still needed once the subprogram has finished, the subprogram must return it so the caller can store it in its own variable. The other option is to keep it in a global variable, which is covered in Global Declaration. Reaching for the local name after the call leaves you with a name that no longer exists:
def ticketCost(adults, children):
total = adults * 9 + children * 5
return total
cost = ticketCost(2, 3)
print(cost)
print(total)Output:
33
NameError: name 'total' is not defined (line 7)A global declaration lets a subprogram change a global variable. It is written with the keyword global followed by the variable name.
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 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.
Scope is the part of a program where a variable can be used. When you create a subprogram, decide where its data needs to be seen: only inside that subprogram, or across the whole program.
Use a local variable when the value is needed only inside one subprogram. This keeps the subprogram self-contained, so you can reuse it in another program without its variable names clashing with names in the code that calls it. It also reduces unintended interference: another part of the program cannot accidentally read or change a local variable while the subprogram is doing its job.
Use a global variable only when a value must be shared by several subprograms or several parts of the program. Global variables need care. Because many parts of the program can read or change them, their value can be altered in one place and used somewhere else, which makes the program's behaviour harder to track and debug.
Use a local variable for data needed inside one subprogram; use a global variable for data needed across the whole program. Local should be your usual choice. Being inside a subprogram does not make a variable global — a variable is local because it is created inside the subprogram, and you should only create it there when nothing outside needs it.
In the example, hall_capacity is global because both subprograms need the same hall capacity. free is local to check_group() because no other part of the program needs it.
hall_capacity = 120 # global: needed by both subprograms
def seats_left(booked):
return hall_capacity - booked
def check_group(size, booked):
free = seats_left(booked) # local: only needed here
if size <= free:
print("Group can enter")
else:
print("Hall is too full")
check_group(8, 110)Output:
Group can enter