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
= 299792458 # speed of light: meters / second ** -1
C = 9.1093837015 * 10 ** -31 # mass in kg
MASS_ELECTRON
# Mathematical constants
= 3.1415926535 # pi
PI = 1.6180339887 # phi (golden ratio)
PHI
# Unit conversions
= 3.280839895
FEET_PER_METER = 1.852
KM_PER_NAUTICAL_MILES
# Other constants
= 12 EGGS_PER_CARTON
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.