Understanding Python Constants
In Python, a constant is a type of variable whose value is not meant to be changed. You use constants to store values that you know should remain the same throughout your program.
Using constants makes your code safer and easier to understand. It helps prevent accidental changes to important data, such as the value of Pi (3.14159) or a maximum number of login attempts (5).
Unlike some other programming languages, Python does not have a strict, built-in feature to make variables unchangeable. Instead, Python developers use a naming convention. This is an agreement among programmers to signal that a variable should be treated as a constant.
The Naming Convention for Constants
The rule is simple and important: To declare a constant, you write the variable name in all uppercase letters. Use an underscore (_) to separate words.
PI = 3.14159TAX_RATE = 0.07WEBSITE_NAME = "My Awesome Site"MAX_LOGIN_ATTEMPTS = 3
Want to master Python fundamentals? This lesson is part of our Free Python course covering variables, data types, functions, and more.
Explore this free Python course →Exercise 1: Define and Print a Constant
We will start with a simple example. Create a constant named PI with the value 3.14159 and then print it to the console.
# This is the example solution
PI = 3.14159
print("The value of PI is:")
print(PI)
Your output will appear here...
Exercise 2: Testing the Constant "Rule"
As we mentioned, constants are a convention, not a strict rule enforced by Python. What happens if you try to change one? Let's find out.
In the box below, define TAX_RATE = 0.05 and print it. Then, on a new line, re-assign it to 0.07 and print it again.
TAX_RATE = 0.05
print(f"The original tax rate is: {TAX_RATE}")
# Now we try to change it...
TAX_RATE = 0.07
print(f"The new tax rate is: {TAX_RATE}")
Your output will appear here...
You're making great progress! Ready to tackle more Python challenges with real-world Exercise?
Python ExerciseThe Purpose and Benefits of Using Constants
You might wonder, "If they can be changed, why should I use them?" Using constants is a critical part of writing clean, professional, and maintainable code. Here’s why:
- Readability: Code is much easier to read. Seeing
if credits < MIN_CREDITS:is much clearer thanif credits < 30:. The number 30 is a "magic number" - its meaning is unclear without context. - Maintainability: Imagine you used
0.05as a tax rate in 20 different places in your application. If that rate changes, you must find and replace all 20 instances. With a constant, you only change it once at the top of your file (e.g.,TAX_RATE = 0.06). - Error Prevention: It signals to you and your teammates that "This value should not be modified." This prevents you from *accidentally* changing a value that should always stay the same.
Learn Python the Right Way
- 50+ hands-on coding exercises
- Real-world projects and applications
- Learn best practices from industry professionals
Advanced Concept: Constants and Mutable Data Types
This is a common point of confusion. It is important to understand that "constant" and "immutable" are not the same thing.
- Immutable means the object *itself* cannot be changed. Integers, strings, and tuples are immutable.
- Constant is a *naming convention* for a *variable*. It means the variable should not be *re-assigned* to point to a new value.
What happens if your "constant" variable points to a *mutable* object, like a list? We will not re-assign the variable, but can we *change the contents* of the list?
# This is the same code as the prompt.
# Run it to see the result!
ALLOWED_USERS = ["Alice", "Bob"]
print(f"Original users: {ALLOWED_USERS}")
# Let's try to add a user
ALLOWED_USERS.append("Charlie")
print(f"Modified users: {ALLOWED_USERS}")
Your output will appear here...
ALLOWED_USERS still points to the *same list object*, but the list *itself* was changed.
Because of this, if you need a constant collection of items that should never change, it is a best practice to use a tuple, which is immutable:
ALLOWED_USERS = ("Alice", "Bob")
If you tried to
.append() to this tuple, Python would raise an error.
Common Mistakes When Using Constants
Here are a few common pitfalls to watch for:
- Forgetting All Caps: Writing
tax_rate = 0.05creates a normal variable. OnlyTAX_RATE = 0.05is a constant. The visual difference is key for other developers. - Assuming a "Locked" Value: Believing Python will stop you from changing
PI = 3.14. Remember, it is a convention, not a technical restriction. - Using Constants for Variables: A user's
scoreorcurrent_agewill change. These should be variables (e.g.,score), not constants (e.g.,MAX_SCORE).
Knowledge Check: Apply Your Skills
You are building a game. In the editor below, define the necessary variables and constants for the following requirements. Then, print them to see your work.
- The player's current score, which starts at 0.
- The game's title, which is "Super Python Quest".
- The highest possible score, which is 1,000,000.
- A list of level names: "The Forest", "The Cave", and "The Castle".
Here is how a professional developer would define these:
# --- Constants ---
# The game's title will not change.
GAME_TITLE = "Super Python Quest"
# The max score is a fixed rule of the game.
MAX_SCORE = 1000000
# The list of levels is fixed. We use a tuple to make it immutable.
LEVEL_NAMES = ("The Forest", "The Cave", "The Castle")
# --- Variables ---
# The player's score will change often.
player_score = 0
# --- Print Check ---
print(f"Game Title: {GAME_TITLE}")
print(f"Max Score: {MAX_SCORE}")
print(f"Levels: {LEVEL_NAMES}")
print(f"Starting Score: {player_score}")
# Example of changing a variable
player_score = player_score + 50
print(f"Score after first points: {player_score}")
Your output will appear here...
Congratulations! You've Completed This Lesson
You now understand Python constants and how to use them professionally. Ready to continue your Python mastery?
Full Python Course
Master Python with 11+ hours of content, 50+ exercises, real-world projects and get a Certificate.
Enroll Now