Menu

Global & Local Variables

Choosing Variable Scope

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.

Choose local when the data stays inside one subprogram

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.

Choose global only when the value must be shared

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.

A simple rule

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

Practise this