Constants
Constants
In most programming languages there’s a convention for naming constants. Python is no different—and the convention is quite similar to many other languages.
In Python, we use ALL_CAPS for constant names, with underscores to separate words if necessary. Here are some examples:
# Physical constants
C = 299792458 # speed of light: meters / second ** -1
MASS_ELECTRON = 9.1093837015 * 10 ** -31 # mass in kg
# Mathematical constants
PI = 3.1415926535 # pi
PHI = 1.6180339887 # phi (golden ratio)
# Unit conversions
FEET_PER_METER = 3.280839895
KM_PER_NAUTICAL_MILES = 1.852
# Other constants
EGGS_PER_CARTON = 12 Unlike Java, there is no final keyword, which tells the compiler that a constant must not be changed (same for other languages like C++ or Rust which have a const keyword).
What prevents a user from changing a constant? In Python, nothing. All the more reason to make it immediately clear—visually—that we’re dealing with a constant.
So the rule in Python is to use ALL_CAPS for constants and nothing else. Then it’s up to you, the programmer, to ensure these remain unchanged.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.