Constant Variables in Python

Recently, someone asked me about constant variables in Python. I explained with examples. When developing software, it’s often necessary to use values that remain unchanged throughout the execution of the program. These values are known as constants. While Python does not have built-in constant types like some other programming languages, you can still create and use constants effectively. In this tutorial, I will explain the concept of constant variables in Python with examples.

In Python, constants are typically defined using all uppercase letters with underscores separating words to indicate that their values should not change. For example, PI = 3.14159 and GRAVITY = 9.8 are constants. Although Python does not enforce immutability, this naming convention serves as a reminder to programmers that these values are intended to remain constant throughout the program.

What is a Constant Variable in Python?

A constant variable in Python is a type of variable whose value cannot be altered during the execution of a program. Constants are typically used to store values that are meant to remain constant throughout the program, such as configuration values, fixed data points, or any value that should not change once set.

Define Constants in Python

Python does not have a built-in constant type. By convention, constants are usually defined in a module and named using all uppercase letters with underscores separating words.

# constants.py
PI = 3.14159
GRAVITY = 9.8
SPEED_OF_LIGHT = 299792458  # in meters per second

In the above example, PIGRAVITY, and SPEED_OF_LIGHT are constants. Although Python does not enforce the immutability of these variables, naming them in uppercase serves as a reminder to the programmer that these values should not be changed.

Check out Check if a Variable is Defined in Python

Use Constants in a Python Program

Let’s consider a practical example where constants might be useful. Suppose you are developing a program that calculates the area of a circle and the force of gravity on an object. You can use the constants defined above to make your code more readable and maintainable.

Here is the complete Python code.

# main.py
from constants import PI, GRAVITY

def calculate_circle_area(radius):
    return PI * (radius ** 2)

def calculate_gravitational_force(mass):
    return mass * GRAVITY

radius = 5  # in meters
mass = 10  # in kilograms

area = calculate_circle_area(radius)
force = calculate_gravitational_force(mass)

print(f"The area of the circle is: {area} square meters")
print(f"The gravitational force is: {force} newtons")

In this example, the use of constants PI and GRAVITY makes the program easier to understand and maintain.

Check out How to Make a Variable Global in Python?

Constant Variable in Python Examples

Now, let me show you a few examples of how to use constant variables in Python.

For instance, constants related to the US tax system, federal holidays, and state abbreviations can be very useful.

Example 1: US Federal Holidays

# us_holidays.py
NEW_YEAR = "January 1"
INDEPENDENCE_DAY = "July 4"
THANKSGIVING = "Fourth Thursday of November"
CHRISTMAS = "December 25"

Using these constants in a program:

# main.py
from us_holidays import NEW_YEAR, INDEPENDENCE_DAY, THANKSGIVING, CHRISTMAS

def is_holiday(date):
    holidays = [NEW_YEAR, INDEPENDENCE_DAY, THANKSGIVING, CHRISTMAS]
    return date in holidays

date = "July 4"
if is_holiday(date):
    print(f"{date} is a federal holiday in the USA.")
else:
    print(f"{date} is not a federal holiday in the USA.")

Example 2: US State Abbreviations

# us_states.py
ALABAMA = "AL"
ALASKA = "AK"
ARIZONA = "AZ"
# ... more states

def get_state_abbreviation(state_name):
    state_abbr = {
        "Alabama": ALABAMA,
        "Alaska": ALASKA,
        "Arizona": ARIZONA,
        # ... more states
    }
    return state_abbr.get(state_name, "Unknown State")

state_name = "Arizona"
print(f"The abbreviation for {state_name} is {get_state_abbreviation(state_name)}.")

Check out How to Check if a Variable Exists in Python?

Using the Pconst Library

For those who prefer a more enforced approach to constants in Python, the Pconst library can be used. This library allows you to create truly immutable constants.

Here is an example of how to use it.

# Install the library
# pip install pconst

from pconst import const

const.PI = 3.14159
const.GRAVITY = 9.8

try:
    const.PI = 3.14  # This will raise an error
except ValueError as e:
    print(e)

By using the Pconst library, you can ensure that constants remain unchanged throughout your program.

Conclusion

While Python does not have built-in support for constant variables, you can effectively use naming conventions and libraries like Pconst to create and manage constants in your programs. Constants make your code more readable, maintainable, and less prone to errors. In this tutorial, I have explained how to use constant variables in Python with examples.

You may like the following tutorials:

Leave a Comment