Constants
In Python, programmers mark a constant by writing its name in capitals and giving it its value a single time near the top of the program, before any code that uses it. From then on, the capitalised name stands for that value wherever it appears later in the program.
ENTRYFEE = 4
visitors = int(input("How many visitors? "))
print(ENTRYFEE * visitors)
ENTRYFEE = 6
print(ENTRYFEE * visitors)Output when the user types 10:
How many visitors? 10
40
60The name ENTRYFEE is set to 4 at the top and used in the calculation. The capital letters do not make the value fixed — they are simply how a constant is written.
Python does not stop a constant from being changed while the program runs. If a later line assigns a new value to the capitalised name, Python carries the assignment out without any error or warning, as the last two lines of the program show.
The capital letters are a convention: an unwritten agreement that tells any programmer reading the code that the value must not be changed. Because the language will not enforce it, the convention is the only thing protecting the value, so programmers follow it and do not assign a new value to a constant after it has been set.
This also means a capitalised name that is reassigned later in the program is not being used as a constant, even though it looks like one. Its capital letters promise a fixed value that the code then breaks.
OCR GCSE Computer Science · Constants
OCR GCSE Computer Science · Local and Global Variables