In this article, you will learn about python constants. A constant is an identifier whose value cannot change throughout the program execution.
On the other hand, the variable concept is the same as you studied in mathematics. Variable values keep changing while constant’s values are fixed.
In python, you cannot use constants as used in c or in java. You can use constants at the module level but one thing is important to remember is that its value cannot be changed.
Example 1: Python Constants
PI = 3.1415927
SCORE = 95
VOWELS = "A,E,I,O,U"
Rules to write Python Constant
- Write constant in all capital letters
- Two words are separated by an underscore
- Never use special characters
- You can never start constant with a digit.
Example 2: Program to use Python constants
Create a new module named “ConstantModule.py”. Now write and initialize some constants. Make sure all the constants are in capital letters.
ConstantModule.py
# declare constants here
PI = 3.1415927
SCORE = 95
VOWELS = "A,E,I,O,U"
Now create a test file, import the above module, and print constants.
test.py
# import module
import ConstantModule
# print constant values
print(ConstantModule.PI)
print(ConstantModule.SCORE)
print(ConstantModule.VOWELS)
Output
3.1415927
95
A,E,I,O,U