IndentationError: expected an indented block
IndentationError: expected an indented block in Python means python expects an indented block of code directly following a colon (:), but found an empty body or mismatched whitespace.
How do I fix IndentationError: expected an indented block?
To fix IndentationError: expected an indented block in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of an empty block without a pass statement. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does IndentationError: expected an indented block mean?
Unlike languages that use curly braces, Python uses indentation to define code blocks. When Python sees a statement ending in a colon (like if, for, while, or def), the grammar requires at least one indented statement beneath it.
Why does IndentationError: expected an indented block happen?
1. An empty block without a pass statement
You cannot leave an if, for, or def body completely empty.
Breaks
def handle_event(event):
print("Done")Works
def handle_event(event):
pass
print("Done")2. The statement below the colon is not indented
The body must be indented (usually 4 spaces) further than the colon line.
Breaks
for item in items:
print(item)Works
for item in items:
print(item)3. Mixing tabs and spaces
A file with a mix of invisible tabs and spaces causes Python to reject the block.
Breaks
if active:
print("tab")
print("spaces")Works
if active:
print("all")
print("spaces")How to find it in your own code
Check the line directly below the colon. If you intend to leave the function or loop empty for now, put `pass` inside it. Configure your editor to convert tabs to 4 spaces.
Try it: fix this bug
easylast_even([1, 3]) crashes: UnboundLocalError: cannot access local variable 'found' where it is not associated with a value.
def last_even(nums):
for n in nums:
if n % 2 == 0:
found = n
return foundMore challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser โ no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.