CP104: Notes - Constants

A constant is a named value that does not change, or at least does not change while a program is executing. Named constants make programs and functions easier to read and write. Mathematical values such as pi and e are constants, physical values such as c (the speed of light in a vacuum), and the acceleration due to gravity close to the earth (\(9.8 {m/s}^2\)) are also constants. Values such as sales tax percentages can be treated as constants while a program is executing, but constants such as these may have to be updated between program executions if the sales tax is changed by the government.

Unlike many other programming languages, Python does not have a true constant. You can, however, simulate a constant through coding standards. Use all capitals for its name (you may still use numbers and underscore) in order to make the name stand out. (This is the Laurier Way.) NEVER CHANGE THE VALUE OF THIS CONSTANT.

Define constants at the beginning of a module. (i.e. define the constant before any executable code.) In order to be visible a constant must either be defined in the same module in which it is used, or imported into the module in which it is to be used. (Importing is discussed later.)

In the following example, the constant GRAVITY_ACCEL is defined in the module gravity.py:

    
"""
According to Newton's Law the force of gravity for objects
near the earth is mass times acceleration. Acceleration due
to gravity (for the earth) is 9.8 m/s^2.
"""
# Constants
GRAVITY_ACCEL = 9.8   # m/s^2

# Inputs
mass = float(input("Enter mass (kg): "))
time = int(input("Time falling (s): "))

# Calculations
force_calc = GRAVITY_ACCEL * mass
final_velocity = GRAVITY_ACCEL * time

# Outputs
print()
print(f"Force: {force_calc:.2f} kg m/s^2")
print(f"Final velocity: {final_velocity:.2f}")

  

In this example the constant GRAVITY_ACCEL is used in two different calculations. Good naming makes the code more readable, and defining the value in only one place makes it easier to change the calculations - in this case, for example, to add more decimals of accuracy to the value.

All of these previous example constants refer to real-world properties that can be 'named'. What about values that are more difficult to name? For example, conversion from Celsius to Fahrenheit involves the formula:

    
fahrenheit = 9 / 5 * celsius + 32

  

The value 32 is the Fahrenheit freezing point of water, and could be given a name - for example, FAHRENHEIT_FREEZING. However, the ratio 9/5 is just a mathematical ratio. That's fine - we can give it a name that makes it clear it is a ratio:

    
# Constants
FAHRENHEIT_FREEZING = 32
F_C_RATIO = 9 / 5    # Fahrenheit to celsius ratio

fahrenheit = F_C_RATIO * celsius + FAHRENHEIT_FREEZING

  

Note the use of an in-line comment to make the meaning of the constant clearer. Further, you do not have to actually calculate the ratio - simply state it and let Python calculate it for you.

What about inconstant constants? i.e. can values that do not arise from fundamental properties of the universe be treated as constants? If these values change only rarely, and never during a particular program run, yes. Tax rates, for example, even though they do change upon occasion (particularly when a government is looking for votes), are unchanged long enough to be treated as constants for most programs. When a tax change is announced, then the program must be updated to match.

    
# Constants
HST = 13 / 100  # Harmonized Sales Tax % in Ontario

price = float(input("Enter price: $"))
total = price + price * HST
print(f"Total cost: ${total:.2f}")

  

Again, the use of a common acronym for a constant makes this program more readable and easier to update.

The Constant Checklist

When using constants, make sure you've done the following:
Used a meaningful, easily readable name. Constants named with single letters such as X and Y are rarely good names, except perhaps in certain formulas. Add an in-line comment to the constant definition if it helps.
Write the constant name in all UPPER CASE. Conversely, make sure that all other variables used in the program are entirely in lower case. Separate words with an underscore (_).
Assign values to a constant once and only once at the top of a module. All constants should be grouped together. Put the comment
# Constants
at the top of the module, after the documentation and imports. Never change the value of a constant anywhere in the body of the code. Never ask the user for the value of a constant - if you do, it's clearly not constant!