When I was teaching a friend Python for the first time, I skipped straight to loops and conditionals without explaining indentation first, and he got completely stuck on an error he couldn’t decipher. So now, whenever I introduce someone to Python, I start with the absolute simplest possible indentation example before touching anything else. This article is that same starting point, built back up from a single if statement into more advanced real-world patterns.
The Simplest Possible Example
Let’s start as basic as it gets: a single if statement with one line inside it.
age = 20
if age >= 18:
print("You are an adult.")
Output:
You are an adult.
That single line, print("You are an adult."), is indented four spaces relative to the if statement above it. That indentation is what tells Python this print statement belongs inside the if block — it only runs when the condition is true.
If I remove the indentation entirely, Python refuses to run the code at all:
age = 20
if age >= 18:
print("You are an adult.")
IndentationError: expected an indented block after 'if' statement on line 3
Python isn’t guessing here — a colon : at the end of a statement like if, for, while, def, or class always signals “a new indented block must follow.”
Adding an Else Block
Extending the same example, an else block sits at the same indentation level as its matching if, while its own body gets indented one level deeper.
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output:
You are a minor.
Visually, this creates a clear hierarchy: if and else line up vertically at the same column, and their respective bodies are indented consistently underneath each one.
Indentation With Loops
The exact same principle applies to loops. Everything indented under a for or while statement is considered part of that loop’s body.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
print("Done listing fruits.")
Output:
I like apple
I like banana
I like cherry
Done listing fruits.
Notice that print("Done listing fruits.") is not indented under the for loop, so it only runs once, after the loop finishes entirely — not once per fruit.
Multiple Statements in One Block
A block can contain as many lines as needed, as long as they all share the exact same indentation level.
def describe_number(n):
print(f"Analyzing the number {n}")
if n % 2 == 0:
print("It's even")
else:
print("It's odd")
print("Analysis complete")
describe_number(7)
Output:
Analyzing the number 7
It's odd
Analysis complete
Here, three statements sit at the function’s top indentation level (print, if/else, print), while the two print statements inside the if/else sit one level deeper.
Nested Indentation Example
Let’s build a slightly more advanced version showing how indentation stacks when blocks are nested inside each other.
def check_grade(score):
if score >= 50:
print("You passed.")
if score >= 90:
print("Excellent work!")
elif score >= 75:
print("Great job!")
else:
print("Good effort.")
else:
print("You did not pass.")
check_grade(95)
check_grade(60)
check_grade(30)
Output:
You passed.
Excellent work!
You passed.
Good effort.
You did not pass.
Each level of nesting adds four more spaces. The outer if score >= 50: body is indented once; the inner if score >= 90: body is indented a second time, nested inside the first.
Indentation Inside Functions and Classes
Function bodies and class bodies follow identical rules. Everything that belongs to the function or class must be indented consistently underneath its def or class line.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
rect = Rectangle(4, 5)
print(rect.area())
print(rect.perimeter())
Output:
20
18
Notice both methods, area and perimeter, are indented at the same level directly under the class, while the code inside each method is indented one level deeper still.
What Happens With Inconsistent Indentation
This is the exact scenario that trips up most beginners, so let’s look at it directly.
def show_info():
print("Name: Ahmad")
print("Role: Student")
IndentationError: unexpected indent
The second print line has two extra spaces compared to the first, even though visually in some fonts it might look “close enough.” Python has no tolerance for “close enough” — it requires exact, consistent indentation within a block.
Whitespace Counts, Not Just Appearance
One subtlety I always emphasize: what matters is the actual whitespace characters, not how the code merely looks in your editor. If one line uses a tab character and another uses four space characters, and your editor happens to display both as the same visual width, they are still fundamentally different at the character level.
def demo():
print("line with a tab")
print("line with four spaces")
Depending on the exact mix, this raises either a TabError or an IndentationError, even though both lines might appear perfectly aligned on screen.
Practical Real-World Example
Here’s a small, realistic script showing indentation working together across a function, a loop, and a conditional — the kind of structure I write constantly in everyday scripts.
def process_orders(orders):
for order in orders:
print(f"Processing order #{order['id']}")
if order["paid"]:
print(" Status: Ready to ship")
else:
print(" Status: Awaiting payment")
print("All orders processed.")
orders = [
{"id": 101, "paid": True},
{"id": 102, "paid": False},
]
process_orders(orders)
Output:
Processing order #101
Status: Ready to ship
Processing order #102
Status: Awaiting payment
All orders processed.
Indentation Inside List, Dict, and Function Call Continuations
One thing that confused me early on is that not all indentation-looking whitespace inside parentheses or brackets is governed by the block-indentation rules described above. When you split a data literal or function call across multiple lines, Python treats it as one continuous logical line, so you have much more freedom in how you space things out.
def build_profile(name, age, city):
return {
"name": name,
"age": age,
"city": city,
}
print(build_profile("Ahmad", 21, "Lahore"))
Output:
{'name': 'Ahmad', 'age': 21, 'city': 'Lahore'}
Here, the indentation inside the { ... } dictionary literal is purely a readability convention, not a strict rule enforced the same way if/for/def blocks are. I still keep it consistent for my own sanity and for anyone reading the code later, but Python itself is more forgiving here because the opening bracket has not yet been closed, so the tokenizer doesn’t expect a new INDENT/DEDENT pair the way it does after a colon.
A Step-by-Step Walkthrough of a Slightly Bigger Example
Let’s put everything together in one slightly larger, realistic example, and trace through exactly how the indentation maps to logical structure.
def summarize_scores(students):
for name, score in students.items():
print(f"Checking {name}...")
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "F"
print(f" {name} scored {score}, grade: {grade}")
print("Summary complete.")
students = {"Ahmad": 92, "Bilal": 78, "Sara": 45}
summarize_scores(students)
Output:
Checking Ahmad...
Ahmad scored 92, grade: A
Checking Bilal...
Bilal scored 78, grade: B
Checking Sara...
Sara scored 45, grade: F
Summary complete.
Walking through the indentation levels here: the function body sits at one level under def. The for loop’s body sits one level deeper again. Inside that loop, the if/elif/else chain sits at the same depth as the print statements around it, while each branch’s own single line of code sits one level deeper still. And critically, print("Summary complete.") sits back at the function’s top level, not inside the for loop, which is exactly why it only prints once at the very end rather than once per student.
Best Practices for Beginners
- Always use 4 spaces per indentation level — never tabs, and never a mix.
- Configure your text editor to convert the Tab key press into spaces automatically. Every major editor supports this.
- Use an auto-formatter like
blackearly on, so you build correct visual habits from the start rather than fixing errors manually. - When you see
IndentationError, check the line the error references and the line immediately above it — the mismatch is almost always between those two.
Common Mistakes
A very common beginner mistake is indenting the first line of a script that doesn’t belong inside any block:
print("Hello")
IndentationError: unexpected indent
Since there’s no if, for, def, or similar statement before it requesting an indented block, Python has no reason to expect this line to be indented at all.
Another common mistake is forgetting to indent after a colon:
if True:
print("This will fail")
IndentationError: expected an indented block after 'if' statement on line 1
FAQs
Why does Python use indentation instead of curly braces? It’s a deliberate design decision to force the code’s visual layout to always match its actual logical structure, eliminating a class of bugs common in brace-based languages.
How many spaces should a beginner use? Four spaces per level, matching PEP 8, which is also what most editors default to for Python files.
Can indentation be inconsistent between different functions in the same file? Yes — each block just needs to be internally consistent. Function A can use 4 spaces and function B could technically use 2, though this is discouraged for readability; consistency across an entire project is strongly recommended.
What’s the difference between IndentationError and TabError? IndentationError happens when whitespace amounts don’t match expected levels. TabError specifically happens when tabs and spaces are mixed inconsistently within the same block.
Summary
Indentation in Python isn’t decoration — it’s the actual mechanism that defines where a block of code begins and ends. Starting from a single if statement and building up through loops, nested conditionals, functions, and classes, the rule never changes: statements that belong together must share exactly the same indentation level. Getting comfortable with this fundamental concept early on made every other Python topic click into place much faster for me.
References
- Python Language Reference, indentation rules: https://docs.python.org/3/reference/lexical_analysis.html#indentation
- PEP 8 – Style Guide for Python Code: https://peps.python.org/pep-0008/
- Python official tutorial, control flow: https://docs.python.org/3/tutorial/controlflow.html
