1. What is a Variable in Python?
A variable in Python is a named container that stores data in memory. Think of it as a labelled box you can put any value inside, retrieve it later, or replace it with something else.
Unlike languages such as Java or C++, Python is dynamically typed, meaning you don’t need to declare a variable’s type before using it. Python automatically figures out the type based on the value you assign.
In Python, variables don’t actually store values directly. They store references (memory addresses) pointing to objects. This is an important distinction when working with mutable types like lists.
#Python variable — no type declaration needed
name = "Hari"
age = 30
score = 98.5
print(name, age, score)
# Output: Hari 30 98.52. How to Declare and Assign Variables
Python uses the = operator to assign a value to a variable. There is no special keyword (like var or let) required.
# Basic assignment
city = "New York"
population = 8_336_817 # underscores improve readability
is_capital = False
# Re-assigning a variable (and even changing its type!)
x = 10
print(x) # 10
x = "hello"
print(x) # hello ← Python allows this (dynamic typing)Reassigning a variable to a completely different type is allowed but can lead to confusing code. Use it sparingly and with clear intent.
3. Variable Naming Rules and Conventions
Python has strict rules you must follow for clean, readable code.
Mandatory Rules
- Must start with a letter (a–z, A–Z) or an underscore (_)
- Can only contain letters, digits (0–9), and underscores
- Cannot start with a digit
- Case-sensitive:
age,Age, andAGEare three different variables - Cannot use Python reserved keywords (e.g.
if,class,return)
✅ Valid variable names
user_name = "Ram"
_private = 42
totalScore2 = 100
MAX_LIMIT = 500 # constant convention
❌ Invalid variable names (will raise SyntaxError)
# 2user = "Ram" → starts with a digit
# my-name = "Ram" → hyphens not allowed
# class = "Python" → reserved keyword4. Multiple Assignment
Python lets you assign values to multiple variables in a single line, making your code more concise.
# ── Assign the same value to multiple variables ──
a = b = c = 0
print(a, b, c) # 0 0 0
# ── Assign different values in one line ──
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# ── Swap variables without a temp variable ──
x, y = y, x
print(x, y) # 2 1 ← swapped!
# ── Unpack from a list or tuple ──
first, second, third = ["apple", "banana", "cherry"]
print(first) # apple
# ── Extended unpacking with * ──
head, *tail = [10, 20, 30, 40]
print(head) # 10
print(tail) # [20, 30, 40]Variables are the foundation of every Python program. You’ve now learned how to declare, name, type-check, cast, and scope them along with best practices that will make your code clean and professional.
Frequently Asked Questions
Variables in Python
What is the difference between == and is for variables?
What is the difference between a local and a global variable?
