Indentation and Blocks
Python uses consistent indentation, not braces or keywords, to mark where a block of code begins and ends.
Purpose
Every block in Python β the body of a function, an if, a for, a class β is marked by
indentation, not by a pair of braces or an end keyword. Lines at the same indentation level that
follow a line ending in : belong to the same block.
Example
def describe(n: int) -> str:
if n < 0:
return "negative"
return "non-negative"
Both return statements are part of describeβs body because theyβre indented one level deeper
than def. The return "non-negative" line is not part of the if block, because it sits
back at the same indentation as if itself, not deeper.
Behavior notes
- A block is called a suite in the language grammar. A suite is either one or more indented
lines following a
:, or β for a short body β a single simple statement on the same line as the:(if n < 0: return "negative"). Lessons in this tier always use the indented form, since it reads more consistently as programs grow. - Indentation must be consistent within a block, but Python does not mandate a specific width β four spaces is the overwhelming convention (and what every example on this site uses), codified for the standard library and most public code by PEP 8.
- Mixing tabs and spaces in the same file is an error in Python 3 β it raises
TabErrorrather than silently guessing what you meant. - An indented line where none is expected, or a missing indent where one is required, raises
IndentationError, a subclass ofSyntaxErrorβ so, like any syntax error, it prevents the file from running at all rather than failing partway through.
Common mistakes
- Copy-pasting code from a source that used tabs into a file that uses spaces (or vice versa) β
editors typically show both as the same visual width, so the mismatch is invisible until Python
raises
TabError. - Assuming a line βlooksβ indented far enough because of a trailing comment or a wrapped editor window, rather than checking the actual leading whitespace.
Implementation notes
Indentation-defined blocks are part of the language grammar itself (see the specification link below), not a CPython-specific detail β every conforming Python implementation parses source the same way.