Global & Local Variables
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) Edexcel GCSE Computer Science · Global & Local Variables