Indentation — Python's Famous Whitespace Rule
In most languages, indentation is decoration. In Python, indentation is the grammar. This single design decision is responsible for both Python's beautiful readability *and* the error every beginner meets in week one. Ten minutes here saves you a hundred frustrated searches.
The idea: structure through spacing
Other languages mark "inside the if" with braces:
# C-style languages (NOT Python)
if (age >= 18) {
print("You can vote");
print("Bring your ID");
}Python uses indentation instead:
# Python
if age >= 18:
print("You can vote")
print("Bring your ID")The colon (:) announces "a block is starting." The indented lines are the block. When indentation returns to the original level, the block ends. No braces, no end keyword — the shape of the code *is* the logic.
What indentation actually controls
Watch the difference indentation makes:
age = 20
if age >= 18:
print("You can vote") # INSIDE the if — only runs when True
print("Welcome!") # OUTSIDE the if — always runsOutput (age is 20):
You can vote
Welcome!Now change one line's indentation:
age = 15
if age >= 18:
print("You can vote")
print("Welcome!") # now INSIDE the ifOutput (age is 15):
(nothing — both prints are inside the if, which was False)Same code, one space of difference, completely different behavior. Indentation isn't styling — it's meaning.
The rules (there are only three)
if, for, while, def, class, with all end their line with :.The errors you'll meet (and how to read them)
IndentationError: expected an indented block
if age >= 18:
print("You can vote") # ← needs 4 spacesPython expected an indented block after the colon and found none. Fix: indent the line.
IndentationError: unexpected indent
print("hello")
print("world") # ← why is this indented? Nothing opened a blockA line is indented with no reason. Fix: remove the indentation.
IndentationError: unindent does not match any outer indentation level
Two blocks ended at different indent levels. Usually a mix of tab and spaces, or 3 spaces in one place and 4 in another. Fix: re-indent the block uniformly (select it in VS Code, Shift+Tab to dedent, Tab to indent).
Let VS Code do the work
: auto-indents the next line✅ Checkpoint
Next: virtual environments — the last building block before variables, and the habit that separates careful coders from chaotic ones.