Local and Global Variables
Scope describes how far a variable's name reaches through a program: it is the region of code where that name exists, so you can read its value there and, where the language allows, assign a new one. Outside that region the name means nothing to the program, so it cannot be printed, used in a calculation or changed there.
Scope follows from where a variable is created. Every variable in Python is either local or global, and the two words simply describe how far its name reaches.
| Local variable | Global variable | |
|---|---|---|
| Created | inside a sub program | in the main program, outside every sub program |
| Can be used in | that one sub program only | the whole program, including every sub program |
The two scopes are separate, and that is what makes them useful. The main program cannot see a variable that belongs to a sub program, and one sub program cannot see another's variables, so each sub program keeps its working values to itself.
Scope is a general idea in programming, not something special to Python: any high-level language decides which names are visible where. You apply the idea in Python, where it explains how a program behaves.
Constants have scope in exactly the same way, so a constant can be local to one sub program or global to the whole program.
The program below shows scope in action. The value laps lives and dies with the sub program that made it, so the last line cannot reach it.
def count_laps():
laps = 6 # created here, so its scope is this sub program
print(laps)
count_laps()
print(laps) # the main program is outside the scope of lapsOutput:
6
NameError: name 'laps' is not defined (line 6)
Working out a name's scope is what lets you predict what a program will print.
OCR GCSE Computer Science · Local and Global Variables