Many Python programs contain values that are expected to remain the same throughout the execution of the program. For example, the value of π (pi), the number of days in a week, a company’s name, a tax rate, or an application’s default settings rarely change once they are defined.
Writing these fixed values repeatedly throughout a program makes the code harder to maintain. If one of these values needs to be updated, every occurrence must be found and changed.
To solve this problem, Python programs commonly store such fixed values in constants. Defining a value once and reusing it throughout the program improves readability and makes the code easier to maintain.
This tutorial explains what Python constants are, why they are used, how to create them, the standard naming convention, and the best practices for working with constant values.
Introduction to Python Constants
A constant is a variable whose value is intended to remain unchanged throughout the execution of a program. Constants are commonly used to store fixed values that are referenced multiple times within a program.
Some common examples of constants include the value of π (pi), the number of days in a week, tax rates, company names, and application configuration settings.
Unlike regular variables, constants are intended to represent values that remain unchanged. Although Python does not enforce true constants, developers commonly write constant names in UPPERCASE to indicate that they should not be modified.
Example: Declaring Constants
PI = 3.14159
MAX_LOGIN_ATTEMPTS = 5
COMPANY_NAME = "DigiEduTech"
Code Explanation:
PIstores the mathematical value of π.MAX_LOGIN_ATTEMPTSstores the maximum number of login attempts allowed.COMPANY_NAMEstores the company name used throughout the program.- All three values are intended to remain unchanged while the program is running.
Why Use Constants in Python?
Constants help organize your code by storing fixed values in one place instead of repeating them throughout the program. This improves code readability, makes updates easier, and reduces the chances of errors.
Using constants offers several advantages:
- Improves code readability by replacing hard-coded values with meaningful names.
- Makes programs easier to maintain because fixed values are defined in one place.
- Reduces the chances of accidental inconsistencies caused by repeated values.
- Helps eliminate magic numbers from the code.
- Makes the purpose of fixed values easier to understand.
- Encourages writing cleaner and more organized programs.
Constants are commonly used to store values such as mathematical constants, tax rates, discount percentages, company names, application settings, and configuration values.
Does Python Have True Constants?
No. Python does not provide true constants because it does not include a const keyword or any language feature that prevents a variable from being modified after it has been assigned.
Instead, Python relies on a naming convention. Variables that are intended to remain constant are written using uppercase letters. Although Python still treats them as ordinary variables, uppercase names serve as a clear indication that their values should not be changed.
For example, the following variables are intended to be constants:
PI = 3.14159
MAX_USERS = 100
DEFAULT_LANGUAGE = "English"
Even though these values are written as constants, Python does not prevent them from being reassigned. It is the responsibility of the programmer to follow the convention and avoid modifying them after they have been defined.
In other words, constants in Python are based on developer discipline and coding conventions, not on language enforcement.
Naming Convention for Constants in Python
Python follows a standard naming convention to distinguish constants from regular variables. Since the language does not provide a dedicated const keyword, developers use uppercase letters to indicate that a variable is intended to store a constant value.
Following this convention makes the purpose of a variable immediately clear. When other developers see an uppercase variable name, they can easily recognize that its value is expected to remain unchanged throughout the program.
Rules for Naming Constants
- Write the entire constant name in uppercase letters.
- Separate multiple words using underscores (_).
- Choose meaningful and descriptive names that clearly indicate the purpose of the value.
Good Examples
PI = 3.14159
MAX_FILE_SIZE = 10
DEFAULT_LANGUAGE = "English"
COMPANY_NAME = "DigiEduTech"
Code Explanation:
PIstores the mathematical value of π.MAX_FILE_SIZEclearly represents the maximum allowed file size.DEFAULT_LANGUAGEindicates the application’s default language.COMPANY_NAMEstores the company name.
Poor Examples
pi = 3.14159
x = 10
value = "English"
abc = 100
Why These Names Should Be Avoided
piis written in lowercase, making it look like a regular variable.xandabcdo not describe what the values represent.valueis too generic and does not communicate its purpose.
Using descriptive uppercase names improves readability and makes the code easier to understand, especially in larger projects where many developers work together.
How to Create Constants in Python
Creating a constant in Python is similar to creating a regular variable. A value is assigned using the assignment operator (=). The only difference is that the variable name is written in uppercase to indicate that its value should not be changed later in the program.
Example: Creating a Single Constant
PI = 3.14159
Code Explanation:
PIstores the mathematical value of π.- The uppercase name indicates that this value is intended to remain unchanged.
Example: Creating Multiple Constants
WIDTH = 1920
HEIGHT = 1080
FPS = 60
Code Explanation:
WIDTHstores the screen width.HEIGHTstores the screen height.FPSstores the number of frames displayed per second.- These values can be reused throughout the program instead of repeatedly writing the same numbers.
Constants vs Variables in Python
Although constants and variables are created using the same syntax, they serve different purposes. A variable stores data that may change during program execution, while a constant is intended to store a value that should remain the same.
Python treats both constants and variables as ordinary variables internally. The distinction exists only through naming conventions and programming practices.
| Feature | Variable | Constant |
|---|---|---|
| Value | Can change during program execution | Intended to remain unchanged |
| Naming Style | Usually lowercase | Usually UPPER_CASE |
| Python Enforcement | No | No |
| Purpose | Store changing data | Store fixed values |
The primary difference is based on how the values are intended to be used, not on how Python stores them.
Can Constants Be Changed in Python?
Yes. Python allows the value of a constant to be changed because it does not enforce constants at the language level. Even if a variable is written in uppercase, Python still treats it as a normal variable and allows reassignment.
Example
PI = 3.14
PI = 3.14159
print(PI)
Output
3.14159
Code Explanation:
- The first statement assigns
3.14toPI. - The second statement replaces the previous value with
3.14159. - The
print()function displays the updated value.
Although the program runs successfully, reassigning a constant is considered poor programming practice. Constants are meant to represent fixed values, and changing them can make the code harder to understand and maintain.
For this reason, once a constant has been assigned a value, it should generally remain unchanged throughout the program.
Practical Examples of Constants in Python
The following examples demonstrate how constants are commonly used in Python programs. Although Python does not enforce constants, using uppercase variable names for fixed values improves code readability and makes programs easier to maintain.
Example 1: Calculating the Area of a Circle
Objective: Use a constant to store the value of π and calculate the area of a circle.
PI = 3.14159
radius = 5
area = PI * radius * radius
print("Area of the circle:", area)Code Explanation:
PIstores the mathematical value of π.radiusstores the radius of the circle.- The area is calculated using the formula π × r².
- The result is displayed using the
print()function.
Output
Area of the circle: 78.53975Output Explanation:
The program calculates and displays the area of a circle whose radius is 5.
Example 2: Using Constants for Application Settings
Objective: Store application configuration values as constants.
APP_NAME = "DigiEduTech"
DEFAULT_LANGUAGE = "English"
MAX_USERS = 100
print(APP_NAME)
print(DEFAULT_LANGUAGE)
print(MAX_USERS)Code Explanation:
APP_NAMEstores the application name.DEFAULT_LANGUAGEstores the default language.MAX_USERSstores the maximum number of supported users.- These values can be used throughout the application without repeating them.
Output
DigiEduTech
English
100Output Explanation:
The program prints the predefined configuration values stored in the constants.
Example 3: Calculating a Discounted Price
Objective: Store the discount percentage as a constant and calculate the final price.
DISCOUNT_PERCENT = 20
price = 1500
discount = price * DISCOUNT_PERCENT / 100
final_price = price - discount
print("Final Price:", final_price)Code Explanation:
DISCOUNT_PERCENTstores the fixed discount percentage.- The discount amount is calculated.
- The discount is subtracted from the original price.
- The final price is displayed.
Output
Final Price: 1200.0Output Explanation:
The program applies a 20% discount to a product priced at 1500 and displays the discounted price.
Example 4: Using Constants in a Game
Objective: Store game settings as constants.
SCREEN_WIDTH = 1920
SCREEN_HEIGHT = 1080
FPS = 60
print("Screen:", SCREEN_WIDTH, "x", SCREEN_HEIGHT)
print("Frame Rate:", FPS)Code Explanation:
SCREEN_WIDTHstores the screen width.SCREEN_HEIGHTstores the screen height.FPSstores the game’s frame rate.- These values can be reused throughout the game program.
Output
Screen: 1920 x 1080
Frame Rate: 60Output Explanation:
The program displays the predefined screen resolution and frame rate stored as constants.
Example 5: Temperature Conversion
Objective: Use a constant in a temperature conversion formula.
FAHRENHEIT_OFFSET = 32
celsius = 25
fahrenheit = (celsius * 9 / 5) + FAHRENHEIT_OFFSET
print("Temperature:", fahrenheit)Code Explanation:
FAHRENHEIT_OFFSETstores the constant value used in the conversion formula.- The Celsius temperature is converted to Fahrenheit.
- The converted temperature is displayed.
Output
Temperature: 77.0Output Explanation:
The program converts 25°C into Fahrenheit using a predefined constant.
Common Mistakes When Using Constants in Python
Beginners often misunderstand how constants work in Python because the language does not enforce them. Avoiding the following mistakes helps produce cleaner and more maintainable programs.
-
Using lowercase names for constants
Constant names should follow the uppercase naming convention to distinguish them from regular variables. -
Changing the value of a constant
Although Python allows reassignment, modifying a constant defeats its intended purpose and can make the program difficult to understand. -
Assuming uppercase variables cannot be modified
Writing a variable name in uppercase is only a convention. Python still allows its value to be changed. -
Using unexplained numbers throughout the code
Replacing repeated numeric values with descriptive constants makes the program easier to read and maintain.
Best Practices for Using Constants in Python
Following a few simple practices can make your Python programs more organized, readable, and easier to maintain.
- Use meaningful and descriptive uppercase names for constants.
- Define constants near the beginning of the program whenever possible.
- Replace repeated fixed values with named constants instead of hard-coded values.
- Avoid modifying constants after they have been assigned.
- Group related constants together to improve code organization.
- Use comments where necessary to describe important constant values.
Key Takeaways: Python Constants
Here are the key points to remember about Python constants.
- Constants represent values that are intended to remain unchanged.
- Python does not provide true constants or a
constkeyword. - Constants are created using the assignment operator (
=). - Constant names are written in UPPER_CASE by convention.
- Using constants improves code readability and maintainability.
- Avoid changing constant values after they are defined.
- Constants are commonly used for fixed and configuration values.