Constants in Python: The ALL_CAPS Convention
A constant is a value that we intend to keep unchanged while a program is running.
For example:
1PI = 3.14159
2MAX_LOGIN_ATTEMPTS = 3
3DEFAULT_TIMEOUT = 30
Python does not have a special const keyword like some other programming languages.
Instead, Python uses a naming convention:
If a value is intended to remain constant, write its name in ALL_CAPS.
For example:
The uppercase name tells other programmers:
"This value is intended to stay the same. Please don't change it."
Important
Python does not automatically prevent this:
1MAX_USERS = 100
2
3MAX_USERS = 500
The second assignment is allowed by Python.
So:
ALL_CAPS is a convention, not a runtime restriction.
Real-World Analogy
Think about a railway station.
Values that normally stay fixed
The station code is a fixed piece of information.
In Python:
Values that can change
A train's current platform can change:
1Platform 1 → Platform 3 → Platform 5
In Python:
Notice the naming difference:
1STATION_CODE = "NDLS" # Constant convention
2current_platform = 3 # Normal variable
This naming style helps programmers quickly understand how a value is intended to be used.
1. The ALL_CAPS Convention
According to the Python style guide PEP 8, constants are normally written using:
UPPERCASE LETTERS + UNDERSCORES
This style is sometimes called:
Examples
1PI = 3.14159
2
3MAX_USERS = 100
4
5DEFAULT_TIMEOUT = 30
6
7COMPANY_NAME = "MSK Institute"
8
9CURRENCY_SYMBOL = "₹"
For names containing multiple words, use underscores:
1MAX_LOGIN_ATTEMPTS = 3
2DEFAULT_TIMEOUT_SECONDS = 30
3MAX_FILE_SIZE_MB = 25
Avoid this
1maxLoginAttempts = 3
2Maximum_Login_Attempts = 3
3maximum_login_attempts = 3
For a constant, the preferred style is:
2. Constants vs Normal Variables
Let's compare them.
| Type | Example | Meaning |
|---|
| Constant | MAX_USERS = 100 | Intended to remain unchanged |
| Variable | current_users = 45 | Can change during the program |
| Constant | PI = 3.14159 | Fixed value |
| Variable | score = 80 | Can change |
Example:
1MAX_ATTEMPTS = 3
2
3attempts_used = 1
4
5print("Maximum attempts:", MAX_ATTEMPTS)
6print("Attempts used:", attempts_used)
Later, the variable can change:
But we normally don't change:
3. Why Do We Use Constants?
Constants make programs easier to read and maintain.
Imagine you have this code:
What does 0.18 mean?
A new programmer may not know.
Instead, create a meaningful constant:
1GST_RATE = 0.18
2
3price = amount * GST_RATE
Now the code is much easier to understand.
Another example
Instead of:
1if password_attempts > 3:
2 print("Account locked")
Use:
1MAX_LOGIN_ATTEMPTS = 3
2
3if password_attempts > MAX_LOGIN_ATTEMPTS:
4 print("Account locked")
The second version clearly explains what 3 means.
4. What is a Magic Number?
A magic number is a number used directly in code without explaining what it represents.
Example:
What is 1.18?
It might represent an 18% tax, but the code doesn't tell us.
A better approach is:
1GST_RATE = 0.18
2
3total = price * (1 + GST_RATE)
Now the purpose is clear.
Remember
Give important fixed values meaningful names instead of scattering unexplained numbers throughout your code.
5. Using typing.Final
Python also provides Final from the typing module.
It can be used to tell static type checkers and IDEs:
"This name is intended to be assigned only once."
Example:
1from typing import Final
2
3MAX_LOGIN_ATTEMPTS: Final[int] = 3
If you later write:
Python itself does not necessarily stop the program at runtime.
However, tools such as static type checkers can report that the Final variable is being reassigned.
Simple way to remember
1ALL_CAPS
2 ↓
3Human-readable convention
4
5Final
6 ↓
7Static checking hint
So:
1from typing import Final
2
3MAX_USERS: Final[int] = 100
means:
"This value is intended to be final, and type-checking tools should warn if I try to reassign it."
6. A Simple Final Example
1from typing import Final
2
3APP_NAME: Final[str] = "MSK Learning"
4
5MAX_STUDENTS: Final[int] = 100
6
7IS_PRODUCTION: Final[bool] = False
8
9print(APP_NAME)
10print(MAX_STUDENTS)
11print(IS_PRODUCTION)
Output
The important part is:
1MAX_STUDENTS: Final[int] = 100
Here:
MAX_STUDENTS → variable nameFinal[int] → tells static tools this should not be reassigned100 → value
7. Where Should Constants Be Stored?
In a small Python program, constants can simply be placed near the top of the file:
1MAX_USERS = 100
2DEFAULT_TIMEOUT = 30
3COMPANY_NAME = "MSK Institute"
In a larger project, shared constants are often placed in a separate file.
For example:
1my_project/
2│
3├── constants.py
4├── config.py
5├── main.py
6└── users.py
The exact file name depends on the project's design.
Common names include:
1constants.py
2config.py
3settings.py
8. Creating a constants.py File
File: constants.py
1from typing import Final
2
3COMPANY_NAME: Final[str] = "MSK Institute"
4
5CURRENCY: Final[str] = "INR"
6
7MAX_LOGIN_ATTEMPTS: Final[int] = 3
8
9DEFAULT_TIMEOUT: Final[int] = 30
Now another file can use these values.
File: main.py
1import constants
2
3print(constants.COMPANY_NAME)
4print(constants.CURRENCY)
5print(constants.MAX_LOGIN_ATTEMPTS)
Output
This approach prevents you from repeatedly writing the same values in many files.
9. Why Centralize Constants?
Imagine you use this value in five different places:
If you write the value separately in five files, changing it later can become difficult.
Instead, keep it in one place:
Then import it where needed.
This creates a single source of truth.
Simple idea
1 constants.py
2 │
3 ┌───────────┼───────────┐
4 ↓ ↓ ↓
5 main.py users.py login.py
All parts of the application can use the same constant.
10. Constants with Collections
Constants can also contain collections.
For example:
1ALLOWED_ROLES = ["ADMIN", "MANAGER", "INSTRUCTOR"]
The name is uppercase, but the list itself can still be changed:
1ALLOWED_ROLES.append("STUDENT")
2
3print(ALLOWED_ROLES)
Output:
1['ADMIN', 'MANAGER', 'INSTRUCTOR', 'STUDENT']
Why?
Because a list is mutable.
Mutable means:
The contents can be changed after the object is created.
11. Using a Tuple for Fixed Values
If you have a collection of values that should not be changed, a tuple can be a better choice:
1ALLOWED_ROLES = (
2 "ADMIN",
3 "MANAGER",
4 "INSTRUCTOR"
5)
A tuple cannot be changed using methods such as .append().
For example:
1ALLOWED_ROLES.append("STUDENT")
will raise an error because tuples do not have an append() method.
Another example
1HTTP_METHODS = (
2 "GET",
3 "POST",
4 "PUT",
5 "DELETE"
6)
These values are intended to be a fixed collection.
12. Important: Final Does Not Make Objects Immutable
This is a very important concept.
Consider:
1from typing import Final
2
3COLORS: Final = ["red", "blue"]
Final tells static type checkers that the name should not be reassigned.
But the list itself is still mutable.
This can still happen:
So:
1Final
2 ↓
3Prevents/reports reassignment of the name
4
5Final
6 ↓
7Does NOT automatically make a list or dictionary immutable
For a fixed collection, consider using an immutable type such as a tuple:
1COLORS: Final = ("red", "blue")
13. Constant Naming Best Practices
Good examples
1MAX_USERS = 100
2
3DEFAULT_TIMEOUT = 30
4
5COMPANY_NAME = "MSK Institute"
6
7CURRENCY_SYMBOL = "₹"
8
9PI = 3.14159
Avoid
1max_users = 100
2companyName = "MSK Institute"
3DefaultTimeout = 30
For constants, use:
1UPPERCASE_WITH_UNDERSCORES
14. Constants vs Variables — Quick Comparison
| Constant | Variable |
|---|
MAX_USERS = 100 | current_users = 45 |
| Usually ALL_CAPS | Usually snake_case |
| Intended to remain unchanged | Can change |
| Often configuration or fixed values | Usually stores changing data |
Can use Final for static checking | Usually does not need Final |
Example:
1MAX_USERS = 100
2
3current_users = 50
4
5current_users = 75
Here:
MAX_USERS → intended fixed limitcurrent_users → changing value
15. Common Mistakes
1MAX_USERS = 100
2
3MAX_USERS = 200
Python allows this.
Remember:
ALL_CAPS is a convention.
1from typing import Final
2
3MAX_USERS: Final = 100
Final is mainly useful for static analysis.
It does not turn the variable into a special runtime constant.
Instead of:
1if age >= 18:
2 print("Adult")
you can use:
1ADULT_AGE = 18
2
3if age >= ADULT_AGE:
4 print("Adult")
The meaning is clearer.
1from typing import Final
2
3NAMES: Final = ["Amit", "Rahul"]
The list can still be modified.
For fixed values, consider:
1NAMES: Final = ("Amit", "Rahul")
16. A Complete Beginner Example
Let's combine the concepts.
1from typing import Final
2
3# Constants
4SHOP_NAME: Final[str] = "MSK Store"
5CURRENCY: Final[str] = "INR"
6
7GST_RATE: Final[float] = 0.18
8FREE_SHIPPING_LIMIT: Final[float] = 999.0
9SHIPPING_FEE: Final[float] = 70.0
10
11
12def calculate_total(price: float) -> float:
13
14 tax = price * GST_RATE
15
16 if price >= FREE_SHIPPING_LIMIT:
17 shipping = 0
18 else:
19 shipping = SHIPPING_FEE
20
21 return price + tax + shipping
22
23
24price = 500
25
26total = calculate_total(price)
27
28print("Shop:", SHOP_NAME)
29print("Price:", CURRENCY, price)
30print("Final Total:", CURRENCY, total)
Output
1Shop: MSK Store
2Price: INR 500
3Final Total: INR 660.0
Notice how the important fixed values are clearly named:
1GST_RATE
2FREE_SHIPPING_LIMIT
3SHIPPING_FEE
This makes the program easier to understand and maintain.
Quick Revision Summary
1PYTHON CONSTANTS CHEAT SHEET
2
31. Python has no built-in `const` keyword.
4
52. Constants are usually written in ALL_CAPS:
6
7 MAX_USERS = 100
8
93. ALL_CAPS is a naming convention, not runtime protection.
10
114. `Final` can tell static type checkers that a name
12 should not be reassigned:
13
14 MAX_USERS: Final[int] = 100
15
165. `Final` does not automatically make lists or dictionaries immutable.
17
186. Use immutable collections such as tuples when appropriate:
19
20 COLORS = ("red", "blue")
21
227. Shared constants can be stored in:
23
24 constants.py
25 config.py
26 settings.py
27
288. Meaningful constants help avoid magic numbers.
Interactive Quiz• Knowledge Check
Practice Quiz
Which naming style is normally used for constants in Python?
Does Python have a built-in const keyword?
What does Final mainly provide?
Which is a good example of a constant?
Which collection is immutable?
Hands-On Practice Challenge
Create a Python program for a small online store.
Requirements
Create these constants:
1STORE_NAME
2CURRENCY
3GST_RATE
4FREE_SHIPPING_LIMIT
5SHIPPING_FEE
Use ALL_CAPS naming.
Then create a function:
The function should:
- 1
Calculate GST.
- 2
Give free shipping when the price is at least FREE_SHIPPING_LIMIT.
- 3
Otherwise add SHIPPING_FEE.
- 4
Return the final amount.
Example
1from typing import Final
2
3STORE_NAME: Final[str] = "MSK Store"
4CURRENCY: Final[str] = "INR"
5
6GST_RATE: Final[float] = 0.18
7FREE_SHIPPING_LIMIT: Final[float] = 999.0
8SHIPPING_FEE: Final[float] = 70.0
9
10
11def calculate_total(price: float) -> float:
12 tax = price * GST_RATE
13
14 if price >= FREE_SHIPPING_LIMIT:
15 shipping = 0
16 else:
17 shipping = SHIPPING_FEE
18
19 return price + tax + shipping
20
21
22price = 500
23
24total = calculate_total(price)
25
26print("Store:", STORE_NAME)
27print("Final Amount:", CURRENCY, total)
Your Task
Try changing:
to:
Observe how the shipping amount changes.
What You Learned
In this lesson, you learned:
- What a constant is
- Why Python does not have a
const keyword - The
ALL_CAPS naming convention - PEP 8 constant naming
- What
Final does - Why
Final is not the same as runtime immutability - What magic numbers are
- Why constants improve code readability
- How to organize shared constants
- Why tuples can be useful for fixed collections
In the next lesson, we will continue your Python learning journey with Data Types Overview (3: Data Types).
👉 Continue to Next Lesson: Data Types Overview →