Limited Offer
60% OFF on all plans!

Variables & Constants in Python

Understand how variables and constants work in Python: declaration, scope, mutability, reassignment, and best practices.

Introduction to Variables

Variables are named references to objects stored in memory. In Python, you do not declare a variable type explicitly — the type is determined automatically.

1. What is a Variable?

Storing values in memory.

Declaring Variables

Python creates variables when you assign a value. There are no special keywords like var, let, or const.

1. Basic Assignment

Creating and updating variables.

2. Multiple Assignment

Assign multiple variables in one line.

Constants in Python

Python does not enforce constants like JavaScript const. Instead, constants are written in UPPERCASE by convention.

1. Constant by Convention

Using uppercase naming.

Mutability vs Reassignment

In Python, some objects are mutable (can change), others are immutable (cannot change).

1. Mutable Object (List)

Lists can be modified.

2. Immutable Object (Integer)

Integers cannot be modified.

Variable Scope

Scope determines where a variable can be accessed. Python follows the LEGB rule: L → Local E → Enclosing G → Global B → Built-in Python searches variables in this exact order.

1. Local Scope

Variables inside functions exist only within that function.

2. Global Scope

Variables defined outside functions are global.

3. global Keyword

Used when modifying a global variable inside a function.

4. nonlocal Keyword

Used to modify a variable from an enclosing function.

5. LEGB Rule Demonstration

Understanding how Python searches for variables.

Redeclaration & Reassignment

Python does not restrict redeclaration. Assigning again simply updates the reference.

1. Redeclaration

Assigning again overwrites.

Best Practices

Following good naming and structure improves readability and reduces bugs.

1. Recommended Guidelines

Industry standards.