Constant in Python

Lesson 17: Constants in Python
In programming, we often deal with values that should never change — like the value of π (pi)
, the speed of light
, or a tax rate
used across an application. These are called constants.
1. What is a Constant?
A constant is a variable that is intended to remain unchanged throughout a program’s execution. Python, however, does not have a built-in constant type — meaning there’s no strict rule preventing you from reassigning a constant.
Instead, developers rely on naming conventions and discipline to signal that a value should be treated as constant.
Python Constant Naming Convention
By convention:
- Constants are written in
UPPERCASE
letters. - Words are separated using underscores for readability.
✅ Examples:
PI = 3.14159
GRAVITY = 9.81
SPEED_OF_LIGHT = 299792458
MAX_USERS = 1000
Even though you can technically reassign these values:
PI = 3.14 # Allowed, but strongly discouraged
you shouldn’t — as it breaks the rule of treating them as unchangeable.
⚙️ Best Practice: Organizing Constants
For large programs, it’s common to store constants in a separate file, such as constants.py, and import them where needed.
Example:
# constants.py
PI = 3.14159
GRAVITY = 9.81
SPEED_OF_LIGHT = 299792458
Then, in your main script:
# main.py
import constants
print(constants.PI)
print(constants.GRAVITY)
Output:
3.14159
9.81
Advanced Tip
If you want to enforce immutability, you can use techniques such as:
- Named tuples
- Enums (from the enum module) *Custom classes that block reassignment
from enum import Enum
class Constants(Enum):
PI = 3.14159
GRAVITY = 9.81
print(Constants.PI.value) # Output: 3.14159
This makes values accessible and prevents accidental reassignment.
In short:
Python doesn’t enforce constants, but you should use uppercase variable names and avoid reassigning them to make your code clear, readable, and professional.
Your next step is to learn about Special Variables in detail.