Constants
A variable is a named value that can change while a program runs. A constant is a named value that is set to a value once and keeps that value for the whole run. The program reads a constant by its name, and no line in the program gives it a different value.
Use a constant when a value is fixed for the whole run, and a variable when the value changes during the run or is different each time the program runs.
| Question | Constant | Variable |
|---|---|---|
| Can it be given a new value later in the run? | No | Yes |
| When is it useful? | When the value is fixed for the whole run | When the value changes, or differs each run |
| Coach trip example | Seats on the coach | Seats booked so far |
Ask whether the value is fixed for the whole run or changes. If it is fixed, a constant fits. If it changes, or is different each time the program runs, a variable fits. A value that happens not to change during one run is not automatically a constant: if it can be different the next time the program runs, it is a variable. The choice is about the role the value plays in the program, not its data type.
For a coach trip, the number of seats on the coach is fixed for the run, so it can be a constant. The number of seats booked goes up as people book, so it is a variable.
COACHSEATS = 48 # fixed for the whole run
seats_booked = 33 # this will change
spaces_left = COACHSEATS - seats_booked
print(spaces_left)
seats_booked = 41
spaces_left = COACHSEATS - seats_booked
print(spaces_left)Output:
15
7
In the program, COACHSEATS is set once and used in both calculations. seats_booked is given a new value before the second calculation, so it is a variable. The constant is never reassigned; the variable is.
OCR GCSE Computer Science · Constants