Constants represent values that should not normally change during a program. Python follows a naming convention rather than enforcing immutability for ordinary names.
Understanding the Concept
Module-level names written in UPPER_SNAKE_CASE signal that a value is intended to remain stable, such as a conversion factor or fixed configuration limit. Python still permits rebinding such a name, so the convention depends on developer discipline and tooling. For truly immutable data structures, the type of object matters; using an uppercase name does not freeze a list. Type hints such as Final can help static checkers, but runtime enforcement is a separate concern.
When and Why You Would Use This
A distance conversion example separates a fixed conversion factor from a changing measurement. The upper-case name makes the intent obvious to readers.
Practical Example
MILES_PER_KILOMETER = 0.621371
distance_kilometers = 5
distance_miles = distance_kilometers * MILES_PER_KILOMETER
print(round(distance_miles, 2))
Understanding the Example
The result is 3.11. The constant name communicates that the factor is not an input you expect to change during ordinary calculations.
Example Output
3.11
Try It Yourself
Introduce a constant for tax_rate in one of your earlier exercises and use it instead of repeating the literal value.
Common Beginner Mistakes
- Assuming uppercase names are automatically read-only in Python.
- Using vague constant names without describing units or purpose.
- Treating a mutable object as immutable just because its variable name uses uppercase letters.
Key Takeaways
- UPPER_SNAKE_CASE is the usual convention for constants.
- The convention does not enforce runtime immutability.
- Descriptive constant names improve clarity and reduce unexplained numbers.