In Python, indentation is part of the code’s structure, not just its appearance. It determines which statements belong to a loop, conditional clause, or function body. Unlike braces in C, the visible layout and the block boundaries are the same. section 4.1 section 9.1
The core rules are:
- Indent the statements belonging to a clause after its colon. Keep statements in the same block at the same indentation level. section 3.4.2 section 8.10
- Indent again for a nested block. Return to an earlier level when that block ends; no closing brace is needed. section 8.10 section 4.1
- Prefer four spaces per level and no tabs. Python does not mandate that width, but PEP 8 recommends it; mixing tabs and spaces can produce misleading alignment and indentation errors. section 4.11 section 8.10
Following the blocks
In `if x < 5:`, assignments indented beneath the line run only when the condition is true. An `elif` or `else` at the original level begins another clause. Similarly, in `def fact(n):`, the loop is inside the function, its indented statements are inside the loop, and `return r` is back at the function-body level. section 3.4.2 section 9.1
# This is Python code.
n = 9
r = 1
while n > 0:
r = r * n #1
n = n - 1 #2
The two indented lines form the `while` body. Moving either back to the level of `while` would remove it from the loop. section 4.1
An unexpected indent or a return to a level that matches no enclosing block raises `IndentationError`. A statement can span lines—for example, inside brackets or with a backslash—so not every visually indented line starts a new block. Python also permits a short clause body on the same line after its colon, though that is usually poor style. section 8.10
x = 1 if x == 1: y = 2 z = 2 File "<tokenize>", line 4 z = 2 ^ IndentationError: unindent does not match any outer indentation level
The final assignment unindents to a level that does not match an outer block, illustrating an `IndentationError`. section 8.10





