Python errors / IndentationError

IndentationError in Python

The spaces at the start of a line don't fit the block it belongs to. Python uses indentation to know which lines belong together.

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

Check these first

  1. After a colon, indent. The lines under if, for, while, def and class start 4 spaces further in.
  2. Same block, same spaces. Every line of a block starts in exactly the same column.
  3. Spaces only. Don't mix tabs with spaces. In the editor, the Tab key types spaces.

Causes and fixes

1 Nothing indented after a colon

A line ending in a colon starts a block, and the block's lines must be indented under it. Indent them by 4 spaces.

Broken
age = 20
if age >= 18:
print("Adult")
IndentationError: expected an indented block after 'if' statement on line 2
Fixed
age = 20
if age >= 18:
    print("Adult")
Adult

2 A line indented for no reason

Only the lines inside a block are indented. A line that isn't in one starts at the left edge, like the line before it.

Broken
name = "Ada"
    print(name)
IndentationError: unexpected indent
Fixed
name = "Ada"
print(name)
Ada

3 A line that doesn't line up

When a block ends, the next line has to go back exactly to the column of a block above it, not part of the way.

Broken
for n in range(3):
    print(n)
  print("done")
IndentationError: unindent does not match any outer indentation level
Fixed
for n in range(3):
    print(n)
print("done")
0
1
2
done

4 Tabs mixed with spaces

A tab and some spaces can look the same width and still differ to Python. Indent every line with spaces only.

Broken
for n in range(3):
โ†’print(n)
        print("done")
TabError: inconsistent use of tabs and spaces in indentation
Fixed
for n in range(3):
    print(n)
    print("done")
0
done
1
done
2
done

Still stuck?