Concept Explanation
Most languages group statements with curly braces and treat whitespace as decoration. Python uses indentation itself as the grouping syntax. Getting it wrong is not a style problem — it is a syntax error, or worse, a program that runs and does the wrong thing.
A block is defined by its indentation
if temperature > 30:
print("It's hot") # indented -> inside the if
print("Drink water") # indented -> also inside the if
print("Done") # not indented -> always runs
The colon : opens a block, and everything indented beneath it belongs to that block. The first line back at the outer level ends it.
Compare to a brace language
if (temperature > 30) {
System.out.println("It's hot");
}
Java's braces do the grouping and the indentation is cosmetic. In Python there are no braces, so the indentation carries the meaning.
The rules
| Rule | Detail |
|---|---|
| Standard depth | 4 spaces per level (PEP 8) |
| Consistency | Every line in one block must be indented identically |
| Tabs vs spaces | Never mix them in the same file — Python 3 rejects it |
| What opens a block | Any line ending in : — if, for, while, def, class, try, with |
Why indentation errors are dangerous
An error that stops the program is easy — you get IndentationError and fix it. The dangerous case is indentation that is valid but wrong:
for item in cart:
total = total + item.price
print(total) # runs ONCE, after the loop
for item in cart:
total = total + item.price
print(total) # runs EVERY iteration
Both are legal Python. They do completely different things. No error message will tell you which one you meant.
Empty blocks need pass
Python has no way to express "an empty block" through whitespace alone, so it provides a keyword:
def not_written_yet():
pass # placeholder; without this, IndentationError
Common Mistakes
- Mixing tabs and spaces. The killer bug, because the two look identical on screen. Python 3 raises
TabError: inconsistent use of tabs and spaces. Fix: configure your editor to insert spaces when you press Tab. - Forgetting the colon.
if x > 5without:givesSyntaxError: expected ':'. The colon and the indentation are a pair — you need both. - Indenting the first line of a file. Top-level code must start at column zero. A stray leading space produces
IndentationError: unexpected indent. - Inconsistent depth within one block. Indenting one line 4 spaces and the next 2 raises
IndentationError: unindent does not match any outer indentation level. - Putting a line inside a loop that belonged outside it (or vice versa). Silent and legal — the bug your tests catch, not the interpreter.
Best Practices
- Set your editor to insert 4 spaces on Tab. In VS Code: enable "Insert Spaces" and set Tab Size to 4. This eliminates the entire tab/space class of bug.
- Turn on whitespace rendering while you are learning, so you can see the difference between a tab and four spaces.
- Keep nesting shallow. More than three levels of indentation is a sign a function should be extracted.
- Let a formatter own it. Tools like
blackreformat indentation automatically and end all arguments about it. - When a loop misbehaves, check indentation before logic. "It only ran once" and "it ran too many times" are usually indentation, not a broken condition.
Practice Exercises
- Inside or Outside: Write a loop over
[1, 2, 3]with aprint()inside the loop, run it, then dedent that sameprint()and run again. Note how many lines each version outputs and explain why. - Trigger Each Error: Deliberately produce an
IndentationError: unexpected indentby indenting a top-level line, then aSyntaxErrorby omitting a colon. Read both messages. - Nested Blocks: Write an
ifinside aforloop, with aprint()inside theif, using 4 spaces per level. Verify the output only appears for items matching the condition.