









Python Constants
Constants
In Python, a constant is a value that should not change once it's been given. For example, if you have a value like the number of days in a week, it always stays the same: 7.
While Python doesn't have a special way to make real constants (like some other languages do), we can still follow a naming rule to show that something is meant to stay the same.
How to Create a Constant in Python
We usually use capital letters for constant names, like this:
DAYS_IN_WEEK = 7
PI = 3.14
APP_NAME = "MyFirstApp"
These are all constants. The capital letters tell us, “Hey! Don’t change this value.”
Using Constants
DAYS_IN_WEEK = 7
print("There are", DAYS_IN_WEEK, "days in a week.")
There are 7 days in a week.
Explanation: We created a constant DAYS_IN_WEEK
and printed its value along with some text. The value 7 was shown because that’s what we stored in it.
What Happens If We Change a Constant?
PI = 3.14
print("Original PI:", PI)
PI = 3.14159 # changing the value
print("Changed PI:", PI)
Original PI: 3.14
Changed PI: 3.14159
Explanation: Python let us change the value, even though we wrote it as a constant. But this is not a good habit. Constants are called that because we should not change them.
So, it's our responsibility as programmers to treat them like fixed values and not update them later.
Tips for Using Constants
- Use capital letters with underscores:
MAX_SPEED
,API_KEY
,PI
- Put constants at the top of your Python file so they are easy to find
- Don’t change their values once they’re set
Conclusion
Constants are values that we decide should not change. Python doesn’t force them to stay constant, but we follow rules to treat them that way.