Python constants

Introduction Reading Time: 10 min

Table of Contents

Description

✅ Constants:
Constants are variables meant to stay unchanged once assigned.
Python doesn’t enforce constants but uses naming conventions (ALL_CAPS).
Typically defined at the top of the file or in a separate config module.
✅ Variable Scope:
Scope determines the visibility and lifetime of a variable.
There are four types of scope in Python:
Local – Inside a function/block.
Enclosing – In enclosing functions (nested).
Global – Declared at the top level of the script/module.
Built-in – Provided by Python (e.g., print, len).
This model is known as LEGB (Local → Enclosing → Global → Built-in).

Prerequisites

  • Understanding of variables and functions.
  • Familiarity with Python code structure and naming conventions.

Examples

Here's a simple program in Python:

 Constants Example:
# Constants are defined in ALL CAPS by convention
PI = 3.14159
APP_NAME = "AwesomeApp"

# These should not be changed, though Python doesn't prevent it
print(PI)

🔸 Variable Scope Examples:
# Global variable
x = 10

def example_function():
    # Local variable (scope limited to this function)
    y = 5
    print("Inside function:", x + y)  # x is accessible due to global scope

example_function()

# print(y)  # ❌ Error: y is not defined outside the function


# Using global keyword
count = 0

def increment():
    global count  # Declare the global variable for writing
    count += 1

increment()
print(count)  # Output: 1

# Nested functions demonstrating enclosing scope
def outer():
    msg = "Hello"

    def inner():
        print(msg)  # Enclosing variable from outer

    inner()

outer()
     

Real-World Applications

Constants:
Defining fixed values like API keys, configuration settings, and conversion factors.
Used in machine learning for learning rates, thresholds, etc.
Variable Scope: Helps organize code and prevent unintended changes.
Enables encapsulation in object-oriented programming.
Useful in closures, decorators, and multi-layered logic.

Where topic Can Be Applied

Web development: Managing session/global states.

Game development: Constants for speed limits, physics rules.

Data science & ML: Managing scoped variables in functions/classes.

Scripting: Use of constants in configuration files.

Security: Storing keys and credentials securely with limited scope.

Resources

Topic video source

A comprehensive video

Watch

Python pdf

pdf on topic

Visit

Interview Questions

Does Python have a built-in keyword for constants?

How do you indicate a constant in Python?

What are the four types of variable scope in Python?

What is the global keyword used for?

Explain the LEGB rule with an example.

Can you access a local variable outside its function?