Menu

Local and Global Variables

Global variables

A global variable is a variable created in the main program, outside every sub program definition, usually by an assignment near the top. Because it belongs to the whole program rather than to a single sub program, every part of the program is able to reach it.

Its scope is the whole program, so both the main program and every sub program can read its value. A procedure can access a global variable with no special statement or declaration and with nothing passed in: Python looks for a local variable first, finds none, and uses the global one instead. The variable also stays in existence for as long as the program runs, so its value does not vanish when a sub program finishes.

bottles_collected = 24  # created in the main program

def report_progress():
    print("Bottles so far: " + str(bottles_collected))

report_progress()
print("Final total: " + str(bottles_collected))

Output:

Bottles so far: 24
Final total: 24

The procedure reads bottles_collected directly, and so does the main program, even though nothing was passed in and the procedure contains no declaration of its own.

Why globals help

Globals suit a value that different sections of the program genuinely need: a shared running total, a setting that several sub programs must follow, or a shared target that more than one sub program checks. The value is set in one place, so there is only one copy to keep correct, and any sub program can use it straight away without it being passed in.

Reading a global and changing one are not the same, though: reading needs nothing special, but assigning a new value to a global from inside a sub program needs a global statement naming that variable.

Practise this