⬅ Previous Topic
Python VariablesNext Topic ⮕
Python Data Types⬅ Previous Topic
Python VariablesNext Topic ⮕
Python Data TypesIn 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.
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.”
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.
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.
MAX_SPEED
, API_KEY
, PI
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. Using constants makes your code easier to read and understand.
⬅ Previous Topic
Python VariablesNext Topic ⮕
Python Data TypesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.