Indentation: Whitespace That Runs Your Code

Indentation: Whitespace That Runs Your Code in Python: Most languages group statements with curly braces and treat whitespace as decoration.

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

RuleDetail
Standard depth4 spaces per level (PEP 8)
ConsistencyEvery line in one block must be indented identically
Tabs vs spacesNever mix them in the same file — Python 3 rejects it
What opens a blockAny 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

  1. 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.
  2. Forgetting the colon. if x > 5 without : gives SyntaxError: expected ':'. The colon and the indentation are a pair — you need both.
  3. Indenting the first line of a file. Top-level code must start at column zero. A stray leading space produces IndentationError: unexpected indent.
  4. Inconsistent depth within one block. Indenting one line 4 spaces and the next 2 raises IndentationError: unindent does not match any outer indentation level.
  5. 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 black reformat 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

  1. Inside or Outside: Write a loop over [1, 2, 3] with a print() inside the loop, run it, then dedent that same print() and run again. Note how many lines each version outputs and explain why.
  2. Trigger Each Error: Deliberately produce an IndentationError: unexpected indent by indenting a top-level line, then a SyntaxError by omitting a colon. Read both messages.
  3. Nested Blocks: Write an if inside a for loop, with a print() inside the if, using 4 spaces per level. Verify the output only appears for items matching the condition.