Definition
A variable whose value is intended to remain unchanged throughout the life of a program.
Why It Matters
Constants prevent “magic numbers”—raw digits scattered throughout code with no context. Failing to use them makes code brittle and hard to maintain; if you need to change a tax rate or API limit that’s hard-coded in 50 places, you will inevitably miss one, causing a silent and potentially expensive bug. They provide a single source of truth for system parameters.
Core Concepts
- Naming Convention: Written in ALL CAPITAL LETTERS with underscores (e.g.,
MAX_USERS). - Soft Constraint: Python does not have built-in protection for constants (unlike
constin C++ or Java). A programmer can reassign them, but they should not. - Global Context: Typically defined at the top of a file to be accessible throughout the script.
# Constants are defined at the top level
MAX_USERS = 100
DATABASE_URL = "postgres://localhost/db"
def check_capacity(current_count):
if current_count >= MAX_USERS:
print("Server is full.")