Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • ๐Ÿ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • ๐Ÿ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • ๐Ÿ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • ๐Ÿ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • ๐Ÿ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • ๐Ÿ“ For Each Assignments
    • ๐Ÿ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • ๐Ÿ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • ๐Ÿ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • ๐Ÿ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • ๐Ÿ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • ๐Ÿ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • ๐Ÿ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • ๐Ÿ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • ๐Ÿ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • ๐Ÿ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • ๐Ÿ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • ๐Ÿ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • ๐Ÿ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • ๐Ÿ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • ๐Ÿ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • ๐Ÿ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • ๐Ÿ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • ๐Ÿ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • ๐Ÿ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • ๐Ÿ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

๐Ÿ“Œ Python Constants: Complete Guide with Examples

Python Constants - Complete Guide

Constants are values that never change โ€” the foundation of reliable Python programs.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
We are a team of Python developers, data engineers and data scientists with years of real-world experience. We have built production applications. We have tackled complex problems. We have helped teams ship better code. What drives us? Teaching โ€” especially that moment when things finally click. Our tutorials focus on practical examples and honest guidance. Whether you are just starting out or leveling up we are here to make Python genuinely useful.
๐Ÿ“‘ On this page:
  • What are Constants?
  • Why Use Constants?
  • User-Defined Constants
  • Rules for Declaring Constants
  • Built-in Constants
  • Math Constants
  • @property Decorator
  • namedtuple() Factory
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
๐Ÿ“š What You'll Learn Here
  • What constants are and why they matter in Python
  • User-Defined Constants โ€” creating your own constants
  • Rules for declaring constants โ€” naming conventions
  • Built-in constants โ€” True, False, __name__, __file__
  • Math constants โ€” pi, e, tau, inf, nan
  • @property decorator โ€” creating constant properties
  • namedtuple() โ€” immutable data structures
  • Hands-on practice with the interactive editor

What Are Constants in Python?

In Python programming, a constant is a name associated with a value that never changes during the program's execution. Unlike mathematics constants, programming constants consist of two things โ€” a name and an associated value. The name describes what the constant represents, and the value is the concrete expression of the constant itself.

Once we define a constant, we cannot change its value during the program's lifetime. A real-life example of constants is โ€” the value of PI = 3.14 or the speed of light 3.8ร—10โธ m/sยฒ.

# Examples of constants in Python
PI = 3.14159265359
LIGHT_SPEED = 299792458  # meters per second
GRAVITY = 9.8  # m/sยฒ
LOGIN_ATTEMPTS = 3
DEFAULT_TIMEOUT = 30

๐Ÿ’ก Key insight: While Python doesn't have a dedicated syntax for constants, the convention is to use UPPERCASE names to signal that a variable should be treated as a constant.

Why Use Constants in Python?

A constant is a variable that never changes through the lifetime of a program. The main reason to use constants is to store named variables that have relevant values for the entire program. Constants help programmers protect against accidentally changing values, which can cause hard-to-debug errors.

๐Ÿ“– Improved Readability

MAX_SPEED is easier to understand than a raw number

๐ŸŽฏ Clear Intent

PI clearly communicates the mathematical constant

๐Ÿ”ง Maintainability

Change one value, update everywhere

๐Ÿ›ก๏ธ Low Risk of Errors

Prevents accidental value changes

๐Ÿงต Thread-Safe

Multiple threads can read safely

โœ… Advantages Summary:
โ€ข Improved Code Readability โ€” Constants make your code self-documenting
โ€ข Clear Communication of Intent โ€” Other developers understand your code
โ€ข Maintainability โ€” Update values in one place
โ€ข Low Risk of Errors โ€” Prevents accidental modifications
โ€ข Thread-Safe Data Storage โ€” Safe for concurrent access

1. User-Defined Constants

Python doesn't have a dedicated syntax for declaring constants. To declare a constant, we define a variable that should never change. We use naming conventions to tell other programmers that a given variable should be treated as a constant.

Rules for Declaring Constants

i.  Constant names should use UPPERCASE letters (e.g., CONSTANT = 90)
ii. Names can contain lowercase (a-z), uppercase (A-Z), digits (0-9), and underscores (_)
iii. Constant names should NOT begin with digits
iv. Special characters (!, #, ^, @, $) are NOT allowed (except underscore)
v.  Names should be meaningful and descriptive (RUN is better than R)
# Example: User-Defined Constants
PI = 3.14
LIGHT_SPEED = 3.8e8
WIDTH = 20
LOGIN_ATTEMPT = 3
DEFAULT_TIMEOUT = 15

Working with User-Defined Constants

# Step 1: Save this as constant.py
PI = 3.14
WIDTH = 20
LOGIN_ATTEMPT = 3
GRAVITY = 9.8

# Step 2: Use constants in another file
import constant as const

r = 2
area = const.PI * r * r
print("Area of circle =", area)
print("Value of width =", const.WIDTH)
print("Login Attempts =", const.LOGIN_ATTEMPT)
print("Value of Gravity =", const.GRAVITY)

# Output:
# Area of circle = 12.56
# Value of width = 20
# Login Attempts = 3
# Value of Gravity = 9.8

2. Built-in Constants

Python provides several built-in constants available in the built-in namespace. Let's explore the most important ones.

a. True and False

True and False are Python's Boolean values. They are instances of int โ€” True has a value of 1, and False has a value of 0. These constants cannot be reassigned.

>>> True
True
>>> False
False
>>> isinstance(True, int)
True
>>> int(True)
1
>>> int(False)
0
>>> True = 44
SyntaxError: cannot assign to True

b. __name__ and __file__ (Dunder Names)

__name__ stores the name of the currently running Python program or module. __file__ contains the path of the script or module from which it is imported.

# first_file.py
print(f"The type of __name__ is: {type(__name__)}")
print(f"The value of __name__ is: {__name__}")

# second_file.py
import first_file
print(f"The type of __file__ is: {type(__file__)}")
print(f"The value of __file__ is: {__file__}")

# Output:
# The type of __name__ is: 
# The value of __name__ is: first_file
# The type of __file__ is: 
# The value of __file__ is: D:\Python Project\second_file.py

3. The @property Decorator

The @property decorator allows you to create class attributes that behave like constants. By defining a property without a setter method, you create a read-only attribute.

class Constants:
    @property
    def PI(self):
        return 3.141592653589793
    
    @property
    def EULER_NUMBER(self):
        return 2.718281828459045

const = Constants()
print(const.PI)           # 3.141592653589793
print(const.EULER_NUMBER) # 2.718281828459045

# Trying to set the value raises an AttributeError
const.PI = 3.14  # AttributeError: can't set attribute

4. The namedtuple() Factory Function

The namedtuple() function from the collections module creates immutable sequence types with named fields. This provides a convenient way to create constants with meaningful field names.

from collections import namedtuple

# Create a Point with named fields
Point = namedtuple("Point", "x y")
point = Point(22, 42)

print(point.x)  # 22
print(point.y)  # 42

# Namedtuple is immutable
point.x = 32  # AttributeError: can't set attribute

# Create a Person with mutable children
Person = namedtuple("Person", "name children")
ajay = Person("Ajay Dev", ["Tanay", "Kajol"])
ajay.children.append("Tina")
print(ajay.children)  # ['Tanay', 'Kajol', 'Tina']

5. Math Constants

Python's math module provides several mathematical constants that are frequently used in programming.

ฯ€ (pi)

3.141592653589793

math.pi

e (Euler's number)

2.718281828459045

math.e

ฯ„ (tau)

6.283185307179586

math.tau

โˆž (infinity)

inf / -inf

math.inf

NaN (Not a Number)

nan

math.nan
import math

# Euler's number
print("Euler's number:", math.e)    # 2.718281828459045

# Pi
print("Value of PI:", math.pi)      # 3.141592653589793

# Tau
print("Value of tau:", math.tau)    # 6.283185307179586

# Positive and negative infinity
print("Positive infinity:", math.inf)   # inf
print("Negative infinity:", -math.inf)  # -inf

# Not a Number
print("NaN:", math.nan)             # nan

Try It Yourself!

Experiment with constants directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
USER-DEFINED CONSTANTS
========================================
PI = 3.14159265359
GRAVITY = 9.8
LOGIN_ATTEMPTS = 3

========================================
MATH CONSTANTS
========================================
math.e = 2.718281828459045
math.pi = 3.141592653589793
math.tau = 6.283185307179586
math.inf = inf
math.nan = nan

========================================
USING CONSTANTS
========================================
Area of circle (r=5) = 78.53981633975
Force (mass=10kg) = 98.0N

โœ… Constants make your code clean and maintainable!
๐Ÿ†

๐ŸŽ‰ You've Mastered Python Constants!

You understand user-defined constants, built-in constants, math constants, and best practices. Constants are essential for writing clean, maintainable Python code.

Quick Quiz โ€“ Test Your Knowledge

Let's see what you've learned about Python constants:

1. What naming convention is used for constants in Python?
2. Which module provides mathematical constants like pi and e?
3. What happens if you try to reassign a value to True in Python?

Frequently Asked Questions

๐Ÿค” Does Python have real constants? โ–ผ

Python doesn't have a dedicated syntax for constants. However, by convention, variables written in UPPERCASE are treated as constants. Python relies on the programmer to respect this convention.

๐Ÿ”ง What is the @property decorator used for? โ–ผ

The @property decorator allows you to define a method that can be accessed like an attribute. By not providing a setter method, you can create read-only constants that cannot be modified.

๐Ÿ“ What's the difference between math.pi and math.tau? โ–ผ

math.pi is the ratio of a circle's circumference to its diameter (โ‰ˆ3.14), while math.tau is the ratio of a circle's circumference to its radius (โ‰ˆ6.28), which is equal to 2ฯ€.

๐Ÿ“š Where to Go From Here

Now that you understand Python constants, here are some related topics to explore:

๐Ÿ“Š Data Types

Review Python data types

๐Ÿ”ง Operators

Learn about Python operators

๐Ÿ“‹ Assignment Statements

Understand assignment in Python

๐Ÿ“– Related Tutorials
  • Data Types in Python
  • Operators and Expressions
  • Variable and Identifiers
  • Assignment Statements
Previous: Operators and Expressions Next: Assignment Statement โ†’