Const In Python In Simple Words

Most of the time, in any programming language, we store values in variables. But what if we don’t want to change the values of those variables for the whole program? In order to do it, we can create constants or const in Python.

In this tutorial, we will learn what a constant is, how to use the constant, and where to use the constant with examples.

What is const in Python?

const or constant in Python coding is like a variable that holds a value that cannot be changed during the program execution.

Constants are usually declared and assigned in different files or modules and are rarely used in Python. The constant helps to hold some value for the whole program.

Constants in Python

Constants in Python works the same as global variable functions, it holds values and cannot be changed. But unfortunately, Python doesn’t support constant.

Capital letters identify or treat the variable as constant, So, we have to capitalize the variable name.

Example:

# declare and assign in a separate file called constant.py
# the variables below is one of the examples of constant values (which cannot be changed)
PI = 3.14
GRAVITY = 9.8
DOB = "12-14-95"
PLANK = 6.62607015
ID_NUMBER = 7429148

After creating the constant.py file, inside the main.py import the constant.

# this is the main.py that calls the constant variables
import constant

print(constant.PI)
print(constant.GRAVITY)
print(constant.DOB)
print(constant.PLANK)
print(constant.ID_NUMBER)

Python Class Variables

Python class variable is the same for all of the objects in the class. They are only declared when the class is made, not in any of its methods. Since these Python class variables belong to the class itself, all instances of that class can use them.

class Food:
    vegetable_name = "Eggplant"

Here, the value “Eggplant” is given to the variable vegetable_name inside the class called Food.

Python Private Variables

In Python, there are no private instance variables that can’t be used outside of an object.

Private variables do not exist in Python, so for best practices, programmers start any variable or method with two underscores character to make it private.

A variable called “__scores” will be seen as a private or non-public variable.

How to get the types of Variables in Python

The type() method returns the data type of a variable.

Additional information from Python Documentation, with one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

x = 50
y = "Python"
print(type(x))
print(type(y))

Output:

<class 'int'>
<class 'str'>

How do you use const in Python?

The Const statement is used to declare and set the value of a constant. By designating a constant, a value is given a meaningful label. A constant cannot be updated or assigned a new value after it has been declared.

What is const used for?

Const or constant is used if the programmer doesn’t want to change or modify the value that is assigned to constant.

It is known that constant variables are used to store values like the value of constants pi, plancks, id numbers, etc. But in Python, constants do not work like in any other programming language. To treat a variable as a constant, programmers name their variables in uppercase characters.

Also read: Python Print List with Advanced Examples

What is constants in OOP?

A constant in OOP is a variable that can’t be changed. Once you define and assign a value to a constant, that value will never change again.

How to declare constant in Python?

In Python, we can’t declare a variable as a constant. That is because Python doesn’t support built-in constant types. But what we can do is treat a variable as a constant in a specific practice.

Types of literals in Python

Literals in Python are the raw data that you give to variables or constants when you’re coding. Literals come in five main types: string literals, numeric literals, boolean literals, literal collections, and a special literal called None.

What is the Difference between Constant and Variables?

A constant has a fixed value that cannot be altered by any variable. While a variable refers to a value that can be altered over time.

The difference between a variable and a constant is shown in the table below. It will help you understand their differences and uses.

ConstantVariables
Constant values cannot be changed.Variable values can be changed.
Most constant values are written in number literals.Variables are written and different literals: string, numbers, boolean constant, etc.
Constants represent known values in inline programming and expressions.Variables represent unknown values.
Constant is not applicable in some programming languages.Variable is supported in every programming language.
Difference between Constant and Variables

Summary

In summary, Python does not support constants or does not have built-in constant types. Instead, what people do is treat a variable as a constant by applying some formats, like naming it in uppercase.

Finally, we can now use Python const in an actual program. To practice what you’ve learned in this tutorial, we have an Online Python Compiler for you to test out some code!

Related Python Tutorials

Common use cases for Const

  • 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.

Frequently Asked Questions

What Python version does this tutorial target?
This tutorial targets Python 3.10 or higher. Most examples work on 3.8+, but newer features (match statements, pipe union types, structural pattern matching) need 3.10+. For deep learning content, Python 3.11 is recommended for best performance.
How do I install Python for this tutorial?
Download Python 3.11 or higher from python.org. On Windows, tick ‘Add to PATH’ during install. On Mac use Homebrew (brew install python). On Linux use your package manager or pyenv for version management.
Do I need pip and virtual environments?
Yes. pip comes with Python. For any project beyond a single script, create a virtual environment: python -m venv venv, then activate and pip install dependencies. This keeps project libraries isolated.
Can I use this in a Jupyter notebook or Google Colab?
Most examples run in both. Colab is great for ML tutorials since it provides free GPU access. Jupyter is better for local iterative development. Just paste the code into a cell and run.
Where can I find more Python practice projects?
Browse itsourcecode.com Python Projects for 250+ free capstone-ready systems (sentiment analysis, image classification, chatbots, LangChain apps). Each includes full source code, dataset links, and installation instructions.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment