Brainlag
  1. Library
  2. Debugging
  3. Python

IndentationErrorWhat is an IndentationError?

Python uses indentation to know which lines belong to an if, a loop or a function. An IndentationError means the spaces at the start of a line do not fit.

Python5 min

What IndentationError means

Output
IndentationError: expected an indented block after 'if' statement on line 2

In Python, the spaces at the start of a line are part of the code. Every line inside an if, loop or function is indented by the same amount, usually 4 spaces. An IndentationError means a line's indent does not match any block Python can see.

The three messages you will meet:

  • expected an indented block: a line ending in : has nothing indented under it.
  • unexpected indent: a line is indented for no reason.
  • unindent does not match any outer indentation level: a line was moved back, but not to a level that exists.

How to find it

Go to the line number and look at its left edge. Compare it with the line that opened the block (the one ending in :). Lines inside the block line up with each other, and the line after the block lines up with the opener. Mixing tabs and spaces can look right and still fail, so let your editor indent for you.

Run it: an empty if

Press Run and read the error from the bottom up.

main.py to run
lives = 0
if lives == 0:
print("Game over")

Go that is in the wrong place

Each player should get a Ready: line, then Go! should print once at the end. The program will not run. Fix the indentation.

exercise_1.py to run
for player in ["Ana", "Ben", "Cleo"]:
    print("Ready:", player)
  print("Go!")

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.