How to Fix "IndentationError: expected an indented block" in Python
Sooner or later every Python beginner sees this message:
IndentationError: expected an indented block
It looks scary but it is one of the easiest errors to fix. Python uses spaces at the start of a line to decide which lines belong together. Other languages use curly braces; Python uses indentation.
Cause 1: Nothing indented after a colon
Any line ending with : (if, else, for, while, def) must be followed by at least one indented line.
# Wrong
if hp > 0:
print("Still standing")
# Right
if hp > 0:
print("Still standing")
The standard is 4 spaces. Most editors insert them when you press Tab.
Cause 2: An empty block you plan to fill later
Sometimes you write the if first and the body later. Python still needs something there. Use pass, which means "do nothing for now":
if hp == 0:
pass # TODO: game over screen
Cause 3: Mixing tabs and spaces
Two lines can look perfectly aligned yet one uses a tab and the other uses spaces. Python 3 refuses to guess and raises TabError or IndentationError. Fix it by retyping the indentation with spaces only, or use your editor's "convert indentation to spaces" option.
The cousin: "unexpected indent"
IndentationError: unexpected indent is the opposite problem: a line is indented when it should not be.
# Wrong
name = "Pyrocub"
print(name)
# Right
name = "Pyrocub"
print(name)
A quick checklist
- Does every line ending in
:have an indented line under it? - Are all lines in the same block indented by the same amount?
- Are you using spaces only?
Read the line number in the error message too. Python points at the line where it noticed the problem, which is usually the line just after the real mistake.
Want to practise until indentation becomes automatic? The if / else lesson in Code Monsters Academy gives instant feedback on exactly this.