Menu

Constants

Identifying and Improving Constants

When you read a program, look for a constant: a name in capital letters that is given a value once, near the top of the program, and is not given a new value later. For example, TICKET_FEE set to 4.5 and then used in a calculation is being used as a constant.

A capitalised name that is reassigned later is not being used as a constant, even though it looks like one. Once a later line assigns a new value to that name, the programmer is treating it like a variable; the capital letters are only a signal, and they do not stop the name being changed.

Replacing a repeated fixed value

A fixed value such as 0.05 can appear again and again in a program. A bare value like this does not explain what it means, and if it needs to change, you must find and edit every copy. To improve the program, replace the repeated fixed value with a constant: set it once near the top with a meaningful capitalised name, then use the name throughout instead of writing the value again and again. The repeated bare values disappear, so the program is easier to read and check, and a change is made in one place only.

pages = int(input("How many pages? "))
print("Single: " + str(pages * 0.05))
print("Double: " + str(pages * 2 * 0.05))

Output when the user types 20:

How many pages? 20
Single: 1.0
Double: 2.0

The first program writes 0.05 twice, so it is hard to tell what the value is for, and a change would mean editing two lines. In the improved program, COST_PER_PAGE is set once and used twice, so the price is easy to find and change. It is being used as a constant because it is set once and only read afterwards.

COST_PER_PAGE = 0.05
pages = int(input("How many pages? "))
print("Single: " + str(pages * COST_PER_PAGE))
print("Double: " + str(pages * 2 * COST_PER_PAGE))

Output when the user types 20:

How many pages? 20
Single: 1.0
Double: 2.0

Practise this