Menu

Constants

Benefits of Constants

Constants are named values that are intended to stay fixed while a program runs. Using them has three main benefits: the program is easier to read, easier to change and less likely to contain mistakes. These benefits do not make the program run faster or use less memory.

Readability

A meaningful constant name tells you what a value represents. In a line such as fee = 6 * 12, the 12 could be a price, a number of weeks or a distance. If the code uses CLUBFEE instead of the bare 12, you can see that 12 is the fee charged to join a club. The name explains the value wherever it is used, so you do not have to guess.

Maintainability and fewer mistakes

A constant is intended to be set once. If the value needs to change, you edit the line that sets the constant, and every place that uses the constant gets the new value. This is maintainability: the program is easier to keep correct as requirements change. If the fixed value were typed again and again, you would have to find and change every copy. Missing one would leave part of the program using an old value.

Writing the value once also helps prevent mistakes. You cannot mistype a second copy as 120 instead of 12, or as 12.0 instead of 12, because there is no second copy. Replacing a repeated fixed value with a constant therefore puts the value in one place and uses its name throughout.

AspectRepeated bare valueNamed constant
Reading the codeThe purpose of the number may be unclear.The name shows what the value represents.
Changing the valueEvery copy must be found and edited.Only the line that sets the constant is edited.
Risk of mistakesCopies can be typed differently.The value is written once.
CLUBFEE = 12
junior_amount = 4 * CLUBFEE
senior_amount = 7 * CLUBFEE
print("Junior members:", junior_amount)
print("Senior members:", senior_amount)

Output:

Junior members: 48
Senior members: 84

Here CLUBFEE is used in two calculations: one for junior members and one for senior members. If the club changes its fee, only the first line needs editing; both amounts then use the new fee. The constant name also makes the purpose of the number clear to anyone reading the code.

Practise this