4.4 Indentation
Why indentation is part of Python's syntax rather than a style choice, the indentation rules, nested blocks, and the most common IndentationError.
Importance
What Is It?
In Python, indentation is not just a style preference — it is the syntax that defines block boundaries, replacing the {} braces used by languages like C or Java.
Why Does It Matter?
Getting indentation wrong doesn’t just look bad, it changes (or breaks) what the code actually does.
Indentation Rules
- Use spaces, not tabs (PEP 8 recommends 4 spaces per level) — mixing tabs and spaces raises a
TabError - Every statement inside the same block must use the exact same indentation
- A block is introduced by a line ending in a colon (
:) and must be indented relative to that line
Nested Blocks
What Is It?
A block inside another block (like an if inside a for inside a function), indicated by increasing indentation for each level of nesting.
How Is It Used?
Each additional level of nesting adds one more increment of indentation.
def check_status(code):
if code == 200:
print("OK")
if code < 300:
print("Success range")
else:
print("Error")
Common Indentation Errors
The most common beginner error is inconsistent or missing indentation after a colon:
>>> if True:
... print("bad") # missing indentation after the colon
File "<stdin>", line 2
print("bad")
IndentationError: expected an indented block after 'if' statement on line 1
Quick Interview Answer
“Python uses indentation instead of braces to mark blocks — it’s part of the language grammar, not a style preference. Every statement in the same block must share identical indentation, spaces and tabs can’t be mixed (that raises a
TabError), and PEP 8’s standard is 4 spaces per level.”
Common Mistakes
- Mixing tabs and spaces in the same file — raises a
TabErrorin Python 3 rather than silently guessing. - Using inconsistent indentation widths between sibling statements in the same block, which raises an
IndentationError. - Forgetting to indent at all after a line ending in
:.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form