What are constants ?
Constant means such variable in which changes cannot be made. Variables are created in Python and values are stored in variables. We can change the values stored in variables whenever we want, but there are some programs in which we do not want to make changes in the values stored in variables, hence Constant variables are such variables in which changes cannot be made. Below is a short and simple Python code and its explanation to understand Constant :
GRAVITY = 9.8
COMPANY_NAME = "TechSol"
print("Company Name :", COMPANY_NAME)
print("Earth Gravity :", GRAVITY)
1. GRAVITY and COMPANY_NAME : GRAVITY and COMPANY_NAME are constants because
their names are written entirely in uppercase.
2. Fixed Value : 9.8 and "TechSol" are values that will never change during
the entire program's execution.
3. Readability : Any other programmer looking at the code will immediately
understand that the values of these variables written in uppercase letters are not to be
tampered with or changed anywhere in the code.
Rules for Constants
Since Python does not have a built-in const keyword, its rules are entirely based on naming
conventions and best practices :
1. Constant names must always be in uppercase letters.
True: TOTAL_LIMIT = 100 , False: Total_Limit = 100
2. 2. If the name contains more than one word, only underscores (_) should be used to join
them.
Example: MAX_LOGIN_ATTEMPTS, DATABASE_PASSWORD
3. Like normal identifiers, constant names can never start with a number. They must always start
with a letter or an underscore.
True: PORT_8080 = 8080 , False: 8080_PORT = 8080
4. The use of any special characters (e.g. @, $, %, -) other than the underscore (_) in the name
is strictly prohibited.
5. As a rule, all constants should always be written at the top of the script/file or in a
separate configuration module, not inside a function or loop.
Features Of Constant
1. Improves Readability : Using PI instead of writing 3.14159 repeatedly in the code
makes the code much easier to read and understand.
2. Easy Maintenanc : If a fixed value has to be changed in the future (like tax rate
increases from 5% to 18%), then you don't have to change it everywhere in the code. You have to
change the value of the constant only at one place.
3. Human Discipline Dependent : It is a unique feature of Python that here constants are
completely dependent on the mutual agreement and discipline of the developers, because in the
background they work just like normal variables.
4. Global Scope Utility : Constants are usually defined at the top of the program or in a
separate file (constants.py), so that they can be easily imported anywhere in the entire
project.