How do I create a constant in Python?


The constants and variables are used to store data values in programming. A variable generally refers to a value that can change over time. Whereas, a constant is a type of variable whose value cannot be changed during a program’s execution.

There are only six built-in constants available in Python which are False, True, None, Not Implemented, Ellipsis( ...), and __debug__. Other than these constants, python does not have any built-in data type to store the constant values.

Example

A sample example of a constant is demonstrated below −

False = 100

Output

SyntaxError: cannot assign to False 

False is a built-in constant in python which stores the boolean value false, assigning anything to it is illegal and it will raise a SyntaxError.

But in PEP 8 standards, constants are capitalized. which helps the users to know it's a constant value. If we encounter any variable with all capital letters, we should not change their values by convention, not by rules. Let’s see an example.

Example

The pi is the mathematical constant which is approximately equal to 3.14159. Let’s declare the constant pi value in python.

# declare constants
PI = 3.14159
print(PI)

Output

3.14

In the above example, the maths constant pi is declared using all capital letters.

Example

As mentioned in the Constants section of PEP 8, we should write the name in capital letters with underscores separating words.

# declare constants
LUMINOUS_EFFICACY = 683
VALUE_A = 100
COLOR = 'RED'

print(LUMINOUS_EFFICACY)
print(VALUE_A)
print(COLOR)

Output

683
100
RED

As we see, the constants are also created exactly as the variables. Both the variable and constants follow similar naming rules, the only difference is the constants use uppercase letters only.

Example

Usually, in Python constants are declared in a module. Let’s take an example and create constants.

Declare constants in a separate file and name that file with the .py extension.

Constants.py file

# declare constants

SPEED_OF_LIGHT_IN_VACUUM = 299792458
PI = 3.141592653589793
LUMINOUS_EFFICACY = 683
VALUE = 20

Example.py file

import Constants

print(Constants.VALUE)
print(Constants.SPEED_OF_LIGHT_IN_VACUUM)
print(Constants.PI)

Output

20
299792458
3.141592653589793

In the above example, we have created the Constants.py file which is called the Constants module. Then, we declared some constant values. After that, we create another python file which is an Example.py file and in that file, we imported the Constant module using the import keyword. And finally, accessed the constant values.

The intention of using capital letters is to tell that the current name is treated as a constant. But it does not actually prevent the reassignment of constant values.

Updated on: 15-May-2023

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements