- 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.pie (Euler's number)
2.718281828459045
math.eฯ (tau)
6.283185307179586
math.tauโ (infinity)
inf / -inf
math.infNaN (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.
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:
True in Python?Frequently Asked Questions
๐ค Does Python have real constants? โผ
๐ง What is the @property decorator used for?
โผ
@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