In this tutorial, you will learn about Python Constants. A constant is a kind of variable that has unchangeable values during execution time. In fact, constants in Python are rarely used. Typically, constants are established and assigned to a unique module or file.
Furthermore, constants have two parts, namely a name and a value. The name will give a clear idea of what the constant is, while the value will give an idea of what the constant looks like in real life.
What is a Constants in python?
In Python, Constant is a type of variable that cannot change its value, for instance constant can be thought as a simple container that holds information that cannot be changed or altered.
In addition, you can think of constants as a bag where you can put books that can’t be taken out again.
Assigning value to Python constant
In Python, assigning a value that supports constants are usually declared and assigned in a module. The module is a new file with variables and functions which is imported into the main file.
Inside the module, constants are written with all capital letters and underscores to separate the words.
For a better understanding of this kind of topic, I will give some examples below.
Also read: Const In Python In Simple Words
Example program for declaring and assigning constant
First is to create constant.py. Inside of the file declared two variables with assigning values.
For example:
HEAT = 26.2
PI = 3.14The second thing to do is create a constant object and name it a main.py file. You must import the constant library, then call the two variables in the constant.py file.
For example:
import constant
print(constant.HEAT)
print(constant.PI)Output:
26.2
3.14Basic rules for naming conventions for variables and constants in Python
Names for Python constants and variables should be a mix of lowercase (a-z) or uppercase (A-Z) letters, numbers (0-9) or an underscore (_).
For example:
phoneNumber
email_add
NAME
READ_ONLYFor naming convention, you should have to create a name which is unique and related to the data you are assigning.
For example:
Number is more readable and makes more sense than declaring only a (N).If you want to have two or more words in a variable name, you should put an underscore between them or use a camel case naming convention.
For example:
//underscore
email_add
//camel case naming convention
phoneNumberIf ever, use capital letters to declare a constant for easy identification.
For example:
HEIGHT
WEIGHT
GENDER
NATIONALITY
RELIGION
STATUSDon’t use special symbols which is hard to familiarize.
For example:
@, !, %, *, #, $, etc.Finally, don’t make a variable name that starts with a number.
For example:
123numberGlobal constants in Python
In Python, a global variable is often set at the beginning of the program. In other words, Python variables that are declared outside of a function are called “global variables.”
In addition, a global constant is a literal value that has a name given to it. Like a global variable, you can get the value of a global constant from any script or 4GL procedure in the application to get the object attribute.
For example:
g = 0 # global variable
def add():
global g
g = g + 5 # increment by 2
print("Inside add():", g)
add()
print("In main:", g)Output:
Inside add(): 5
In main: 5Deleting variables
In Python, deleting a variable name is easy to get rid of a variable that is not used. To free up space, we can delete any specific variable by typing del “variable name.”
For example:
g = 26
print (g)
del g
print (g)Concatenating variables
Concatenating variables in Python programming language with different data types is easy. Like a number variable and a Python String variable, we will have to declare the number variable as a string.
Then Python will throw a TypeError if the number variable is not declared as a string variable before it is added to a string variable.
For example:
g = ‘Glenn’
l = 26
print g+lAnother example below will throw a TypeError due to variable g being a string type while variable l is an int type.
To remove this kind of error message, we need to declare the int variable as a string.
For example:
g = ‘Glenn’
l = 26
print(g + str(l))Output:
Glenn26Conclusion
I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials that could help you a lot.
Related Python Tutorials
- Python Print List With Advanced Examples
- Python Pi With Advanced Example
- Python Set Union With Advanced Examples
- Python Rstrip Method With Advanced Examples
- Python Lower Method With Advanced Examples
- Isalpha Python String Method With Advanced Examples
Common use cases for Python Constants With Advanced Examples
- Data pipelines. Python is the standard for ETL, data analysis, and ML workflows.
- Web development. Django and FastAPI power modern web backends and APIs.
- Automation and scripting. System administration, file processing, web scraping, and cron jobs.
- Machine learning. scikit-learn, PyTorch, TensorFlow, Hugging Face for AI/ML projects.
- Educational tools. Python’s readability makes it the go-to teaching language.
Working code example
from typing import Optional
def process_data(items: list[dict]) -> Optional[dict]:
"""Process a list of items and return summary stats."""
if not items:
return None
return {
"count": len(items),
"total": sum(item.get("value", 0) for item in items),
"avg": sum(item.get("value", 0) for item in items) / len(items),
}
# Usage
data = [{"value": 10}, {"value": 20}, {"value": 30}]
summary = process_data(data)
print(summary) # {'count': 3, 'total': 60, 'avg': 20.0}
Best practices
- Use type hints. list[dict], Optional[str], and TypedDict make code self-documenting and enable static analysis.
- Follow PEP 8. Consistent style improves readability. Use black or ruff to auto-format.
- Prefer f-strings. f”{value}” is cleaner than str.format() or % formatting.
- Write tests with pytest. Aim for 70%+ coverage on business-critical modules.
- Use ruff or pylint. Static analysis catches many bugs before code runs.
Common pitfalls
- Mutable default arguments. def f(x=[]) reuses the same list across calls. Use x=None then check.
- Integer division. 5/2 gives 2.5 in Python 3. Use // for floor division.
- Missing self on methods. Class methods need self as first parameter.
- Late binding closures. Loops that create lambdas can capture variables late.
