Variables in Python
Variables are the building blocks of every Python program — named labels that point to values stored in memory. Python's dynamic typing means you never declare a type; the interpreter figures it out at runtime. Master variables and you unlock the foundation of all Python programming.
What is a Variable?
A variable is a named label that points to a value stored in memory.
When Python executes x = 42 it creates an integer object
42 in memory, creates a name x in the
current namespace, and binds that name to the object. Think of a variable as a sticky note placed on
a box — the note has the name, the box holds the data.
# Creating variables — no type declaration needed
x = 42 # int
name = "Alice" # str
price = 9.99 # float
is_active = True # bool
nothing = None # NoneType
# Using the variables
print(name, "has", x, "points") # Alice has 42 points
print(f"Price: ₹{price}") # Price: ₹9.99
print("Active?", is_active) # Active? True
# Both a and b point to the SAME object
a = 100
b = a
print(id(a) == id(b)) # True — same object in memory
# Reassigning b does NOT affect a
b = 200
print(a, b) # 100 200
Variable Naming Rules & PEP 8 Conventions
Python has strict rules (breaking them causes a
SyntaxError) and recommended conventions from
PEP
8
(the interpreter won't complain, but every professional Python developer expects them).
count, Count and COUNT are three separate variables.keyword.kwlist to see them all.user_name, total_price. Avoid
camelCase for variables._count) signals
"internal use". Double underscore triggers name mangling in classes.total_price over tp. Self-documenting names reduce the need for comments.| Variable Name | Valid? | Reason |
|---|---|---|
| user_name | ✓ Valid | snake_case, starts with letter — ideal |
| _count | ✓ Valid | Underscore prefix — signals internal use |
| totalPrice2 | ✓ Valid | Letters + digit (not at start). Works, but camelCase is unpythonic |
| 2fast | ✗ Invalid | Cannot start with a digit — SyntaxError |
| my-var | ✗ Invalid | Hyphen is the minus operator — SyntaxError |
| class | ✗ Invalid | Reserved keyword — SyntaxError |
| my var | ✗ Invalid | Spaces not allowed — SyntaxError |
| π | ✓ Valid* | Unicode letters allowed, but avoid non-ASCII for portability |
# ✓ Good names following PEP 8 ─────────────────────────────────
age = 25
user_name = "Alice"
total_price = 199.99
is_logged_in = True
_internal = "private use"
# ✗ Invalid — these raise SyntaxError (shown as comments)
# 2fast = "nope" # starts with digit
# my-var = 10 # hyphen = minus operator
# class = "CS101" # reserved keyword
# ── Case sensitivity — three completely different variables ────
score = 90
Score = 75
SCORE = 100
print(score, Score, SCORE) # 90 75 100
# ── View all Python reserved keywords ─────────────────────────
import keyword
print(keyword.kwlist)
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
# 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
# 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
# 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
# 'try', 'while', 'with', 'yield']
Assignment — Single, Multiple & Chained
Python's = operator binds a name to a value.
It supports several shorthand forms — multiple assignment, chained assignment, augmented operators, and
starred
unpacking — that make your code concise and expressive.
# ── 1. Basic single assignment ─────────────────────────────────
x = 10
name = "Bob"
# ── 2. Multiple assignment — different values on one line ──────
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Unpack a list or tuple
first, second, third = ["red", "green", "blue"]
print(first) # red
# Swap without a temp variable — Python idiom!
x, y = 5, 10
x, y = y, x
print(x, y) # 10 5
# ── 3. Chained assignment — all names point to the same object ─
p = q = r = 0
print(p, q, r) # 0 0 0
# ── 4. Augmented assignment operators ─────────────────────────
score = 100
score += 10 # score = score + 10 → 110
score -= 5 # score = score - 5 → 105
score *= 2 # score = score * 2 → 210
score //= 3 # score = score // 3 → 70
score **= 2 # score = score ** 2 → 4900
score %= 100 # score = score % 100 → 0
# ── 5. Extended unpacking with star (*) ────────────────────────
nums = [1, 2, 3, 4, 5]
head, *tail = nums
print(head) # 1
print(tail) # [2, 3, 4, 5]
first, *middle, last = nums
print(first, last) # 1 5
print(middle) # [2, 3, 4]
x, y = y, x is Python's idiomatic swap. Python evaluates the right-hand
side as a tuple first, then unpacks — no temporary variable needed.
Dynamic Typing — Variables Can Change Type
Python is dynamically typed: a variable's type is not fixed at declaration. The same name can hold an integer now and a string a moment later. This contrasts with statically typed languages like Java where types are locked at compile time.
# The SAME variable x changes type on each reassignment
x = 42
print(type(x)) # <class 'int'>
x = "hello"
print(type(x)) # <class 'str'>
x = 3.14
print(type(x)) # <class 'float'>
x = [1, 2, 3]
print(type(x)) # <class 'list'>
x = None
print(type(x)) # <class 'NoneType'>
# ── Python vs statically typed languages ──────────────────────
# Java: int x = 5; // type locked forever
# Python: x = 5 // x can be anything, anytime
# ── Duck Typing — Python cares about behaviour, not type ──────
def double(val):
return val * 2
print(double(5)) # 10 (int × 2)
print(double("hi")) # hihi (str × 2)
print(double([1, 2])) # [1, 2, 1, 2] (list × 2)
int and receives a
str, Python won't warn you until it crashes at runtime. Use
type hints and mypy for optional static checking:
def greet(name: str) -> str:
Inspecting Variables — type() and id()
type() returns the class of any object.
id() returns its unique memory address. Together they are your main tools
for understanding and debugging variable behaviour in Python.
x, e.g.
<class 'int'>. Use isinstance(x, int)
for type-checking in production — it respects inheritance.
x
points to. Two variables with the same id share the exact same object.
x and
y point to the same object. Different from
== which checks value equality regardless of identity.
type(x) == T because it
handles subclasses correctly and is considered more Pythonic.# ── type() ────────────────────────────────────────────────────
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type([1,2])) # <class 'list'>
print(type({"a":1})) # <class 'dict'>
print(type(None)) # <class 'NoneType'>
# ── isinstance() — preferred for type-checking ────────────────
x = 42
print(isinstance(x, int)) # True
print(isinstance(x, (int, float))) # True — checks multiple types at once
# ── id() — memory address ─────────────────────────────────────
a = 10
b = 10
print(id(a) == id(b)) # True — CPython caches small ints (-5 to 256)
print(a is b) # True — same object
c = 1000
d = 1000
print(c is d) # False — two separate objects (outside cache range)
print(c == d) # True — same value
# ── Rule: use == for values, is only for None/True/False ──────
val = None
if val is None: # ✓ correct
print("val is None")
a is b → True). Outside that range,
new objects are created each time.
Variable Scope — Local, Global & Nonlocal
A variable's scope defines where in your code it can be accessed. Python resolves names using the LEGB rule: Local → Enclosing → Global → Built-in.
global keyword.# ── Global variable ────────────────────────────────────────────
counter = 0 # global scope
def show_counter():
print(counter) # ✓ Reading a global is fine
show_counter() # 0
# ── Local variable — invisible outside the function ────────────
def greet():
message = "Hello!" # local scope
print(message)
greet() # Hello!
# print(message) # ✗ NameError: not defined here
# ── global keyword — modify a global from inside a function ────
def increment():
global counter
counter += 1
increment()
increment()
print(counter) # 2
# ── LEGB rule visualised ───────────────────────────────────────
x = "global" # G
def outer():
x = "enclosing" # E
def inner():
x = "local" # L
print(x) # local
inner()
print(x) # enclosing
outer()
print(x) # global
# ── nonlocal keyword — modify enclosing scope variable ────────
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = make_counter()
print(c(), c(), c()) # 1 2 3
global. Pass values as arguments and return results — this
makes functions easier to test, debug and reason about.
Constants & the del Statement
Python has no built-in constant keyword. By convention, a name written
in ALL_CAPS signals "treat this as immutable — do not reassign." The interpreter won't
enforce
it, but all professional developers respect it. The del statement removes
a name binding from the current namespace.
# ── Constants defined at module top level ─────────────────────
PI = 3.14159265358979
GRAVITY = 9.81 # m/s²
MAX_RETRIES = 3
BASE_URL = "https://api.example.com"
DEBUG_MODE = False
radius = 7
area = PI * radius ** 2
print(f"Area = {area:.2f}") # Area = 153.94
# ── typing.Final (Python 3.8+) — static checker enforcement ───
from typing import Final
MAX_SIZE: Final[int] = 100
# MAX_SIZE = 200 # mypy reports: Cannot assign to final name
# ── Useful stdlib constants ────────────────────────────────────
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.inf) # inf
# ── del removes the name binding ───────────────────────────────
temp = "temporary data"
print(temp) # temporary data
del temp
# print(temp) # ✗ NameError: name 'temp' is not defined
# Delete multiple variables at once
x, y, z = 1, 2, 3
del x, y, z
# Delete a list element by index
fruits = ["apple", "banana", "cherry"]
del fruits[1]
print(fruits) # ['apple', 'cherry']
# Delete a dictionary key
person = {"name": "Alice", "age": 30}
del person["age"]
print(person) # {'name': 'Alice'}
# Safe access after possible deletion
try:
print(temp)
except NameError:
print("Variable does not exist") # Variable does not exist
Mini Projects — Variables in Action
The best way to cement your understanding is to write real programs. Here are three mini-projects that use everything from this chapter:
Project 1 — Student Grade Calculator
student_name = "Riya Patel"
maths_score = 88
science_score = 92
english_score = 79
TOTAL_SUBJECTS = 3 # constant
total = maths_score + science_score + english_score
average = total / TOTAL_SUBJECTS
if average >= 90: grade = "A+"
elif average >= 80: grade = "A"
elif average >= 70: grade = "B"
else: grade = "C"
print(f"Student : {student_name}")
print(f"Total : {total}/{TOTAL_SUBJECTS * 100}")
print(f"Average : {average:.1f}%")
print(f"Grade : {grade}")
# Student : Riya Patel
# Total : 259/300
# Average : 86.3%
# Grade : A
Project 2 — Temperature Converter
celsius = 37.5 # body temperature
fahrenheit = (celsius * 9/5) + 32
kelvin = celsius + 273.15
print(f"{celsius}°C = {fahrenheit}°F = {kelvin}K")
# 37.5°C = 99.5°F = 310.65K
# Swap using Python's tuple-swap idiom
celsius, fahrenheit = fahrenheit, celsius
print(f"After swap — celsius={celsius}, fahrenheit={fahrenheit}")
# After swap — celsius=99.5, fahrenheit=37.5
Project 3 — Shopping Bill with GST
GST_RATE = 0.18 # constant — 18% GST
item1, price1 = "Laptop", 45000
item2, price2 = "Mouse", 799
item3, price3 = "Keyboard", 1299
subtotal = price1 + price2 + price3
tax = subtotal * GST_RATE
total = subtotal + tax
print("╔═══════════════════════════════╗")
print(f" {item1:<12} ₹{price1:>8,.0f}")
print(f" {item2:<12} ₹{price2:>8,.0f}")
print(f" {item3:<12} ₹{price3:>8,.0f}")
print(" " + "─" * 29)
print(f" {'Subtotal':<12} ₹{subtotal:>8,.0f}")
print(f" {'GST (18%)':<12} ₹{tax:>8,.0f}")
print(" " + "═" * 29)
print(f" {'TOTAL':<12} ₹{total:>8,.0f}")
print("╚═══════════════════════════════╝")
# ╔═══════════════════════════════╗
# Laptop ₹ 45,000
# Mouse ₹ 799
# Keyboard ₹ 1,299
# ─────────────────────────────
# Subtotal ₹ 47,098
# GST (18%) ₹ 8,478
# ═════════════════════════════
# TOTAL ₹ 55,576
# ╚═══════════════════════════════╝
- A variable is a named reference (label) that points to an object in memory — not a container holding the value directly.
- No declaration needed — Python infers the type automatically at assignment time. Just
write
x = 42. - Naming rules: letters, digits (not at start), underscores only. No spaces, hyphens or
keywords. Case-sensitive. PEP 8 convention:
snake_case. - Multiple assignment:
a, b, c = 1, 2, 3. Swap idiom:x, y = y, x. Chained:p = q = r = 0. Star unpacking:head, *tail = nums. - Dynamic typing: a variable can hold any type and change type by reassignment. Use type
hints (
x: int = 5) for documentation and static analysis with mypy. type(x)returns the type.id(x)returns the memory address. Preferisinstance(x, T)for type-checking. Useisonly forNone,True,False.- Scope (LEGB): Local → Enclosing → Global → Built-in. Use
globalto modify a global from inside a function; usenonlocalfor the enclosing scope. - Constants: use
ALL_CAPSby convention. Usetyping.Finalfor static-checker enforcement in Python 3.8+. del varremoves the name binding from the namespace. Accessing it afterwards raisesNameError.
== compares values — "do these two objects
contain equal data?" is compares identity — "do
these two names point to the exact same object in memory?" (id(a) == id(b)).
Use == for value comparisons everywhere.
Reserve is only for singletons: if x is None, if flag is True.
a = b = [] is chained assignment — both a and b point to the same
list object. Appending to a also changes b because they share memory.
a, b = [], [] creates two
separate list objects. Modifying a has no effect on b. For mutable objects (list, dict, set), always use individual
assignments.
Technically yes — list = [1, 2, 3] won't raise an error. But
you've just shadowed the built-in list type. You can no
longer call list() until you del list or restart. This is a very common beginner mistake. Never
shadow built-in names.
Functions that depend on and modify global state are hard to test, debug and reason about — the function's behaviour depends on external state you can't see from its signature. It also makes code order-sensitive and prone to subtle bugs.
The alternative: pass values as arguments and return results. This makes functions pure — the same inputs always produce the same outputs.
Pure Python has no runtime-enforced constant. Your options are:
- ALL_CAPS convention — signals to humans "do not reassign". The interpreter won't stop you.
typing.Final(Python 3.8+) —mypyflags any reassignment as an error.- Frozen dataclasses —
@dataclass(frozen=True)for truly immutable structured data.
x, y = 5, 10 then x, y = y, x, what is the value of x?
type(True) return?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.