Local and Global Variables
A constant is a named value that is set once and never changed. Constants have scope in exactly the same way as variables: put one at the top level of your program, outside every sub program, and it is global; put one inside a sub program and it is local.
A global constant is declared at the top level of your program, outside every sub program, and its name is written in capital letters. Every sub program can read it, so the value is stored in one place only: if the value ever needs to change, you edit one line instead of hunting through the program for every copy.
No global statement is needed to read a global constant inside a sub program. A global statement is only needed when a sub program assigns to a global, and a constant is never assigned to after it is set, so reading works straight away.
PERIOD_MINUTES = 50 # global constant, read by every sub program
def minutes_since_start(periods):
return periods * PERIOD_MINUTES
def minutes_left(periods_done, total_periods):
return (total_periods - periods_done) * PERIOD_MINUTES
print(minutes_since_start(3))
print(minutes_left(2, 6))Output:
150
200
Both sub programs read the same PERIOD_MINUTES, so the length of a period is defined in exactly one place.
A local constant belongs to one sub program and nowhere else. You declare it on a line inside that sub program because the fixed value it holds matters only to that routine. Nothing outside can read it, and it disappears when the sub program ends, so the main program cannot use it at all.
def book_slot(people):
MAX_PER_SLOT = 8 # local constant, only this sub program needs it
if people <= MAX_PER_SLOT:
return "Slot booked"
return "Too many people for one slot"
print(book_slot(4))
print(book_slot(9))Output:
Slot booked
Too many people for one slot
Python does not enforce constants: writing a name in capitals does not stop a later line assigning a new value to it, so keeping a constant constant is the programmer's job.
OCR GCSE Computer Science · Local and Global Variables