Python 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

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. Using constants makes your code easier to read and understand.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You 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.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M