Menu

Local and Global Variables

Benefits of local variables

A local variable earns its place because it makes a sub program easier to write, test, reuse and maintain, not just because it keeps a value tidy.

Self-contained, so testable and reusable

A sub program that uses only its own local variables and its parameters is self-contained: the values it needs from the rest of the program arrive as parameters, so it depends on nothing else. That means you can test it on its own, before the rest of the program is written or working, by simply calling it with some values and checking what comes back. It also means you can copy it into another program and call it there without changing a line, because it carries all its working inside itself.

def lap_time(seconds):
    # minutes and extra are local to this function
    minutes = seconds // 60
    extra = seconds % 60
    return str(minutes) + "m " + str(extra) + "s"

print(lap_time(95))
print(lap_time(200))

Output:

1m 35s
3m 20s

Each call passes in a different number of seconds, yet the function needs no other part of the program to do its job. minutes and extra belong to that one function, so a change to a variable called minutes somewhere else in the program could not disturb them.

Nothing is changed by accident

Because no other part of the program can reach a local variable, nothing outside the sub program can alter it behind your back. If a result comes out wrong, the fault must lie inside that single sub program, so you search a few lines instead of the whole program, and the bug is found faster.

Names can be reused and memory is freed

Local variables also let the same name appear in several sub programs without clashing. Each sub program can use the obvious name for its own job, which makes the code easier to read and to maintain later. Finally, the memory a local variable uses is released when the sub program ends, so a program that runs for a long time does not fill memory with values that are already finished with.

Practise this