In this lesson, you will learn about constants and how to assign a value to a constant in Python, with examples to better understand the topic.
A constant is a sort of variable with an unchangeable value. Consider constants as containers containing the information you cannot modify later. Constants can be compared to a sack for storing books that cannot be replaced once placed inside.
Most of the time, constants are declared and given values in a Python module. In this case, the module is a new file imported into the main file containing variables, functions, and other things. Constants are written inside the module with all capital letters and an underscore between each word. Let’s see an example of declaring a constant and giving it a value below.
Example
PI = 3.14 GRAVITY = 9.8 Create a main.py: import constant print(constant.PI) print(constant.GRAVITY)
Output
3.14 9.8
In the above program, we make a file called constant.py. Then, we assign PI and GRAVITY the same value, make a file called main.py, and import the “constant” module. Lastly, we print the value of the constant.
This concludes the Python Constants lesson. In the next lesson, you will learn Literals in Python and their usage.