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.
Your error
Check these first
- After a colon, indent. The lines under
if,for,while,defandclassstart 4 spaces further in. - Same block, same spaces. Every line of a block starts in exactly the same column.
- 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.
age = 20
if age >= 18:
print("Adult")
IndentationError: expected an indented block after 'if' statement on line 2
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.
name = "Ada"
print(name)
IndentationError: unexpected indent
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.
for n in range(3):
print(n)
print("done")
IndentationError: unindent does not match any outer indentation level
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.
for n in range(3):
โprint(n)
print("done")
TabError: inconsistent use of tabs and spaces in indentation
for n in range(3):
print(n)
print("done")
0 done 1 done 2 done
Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: If / Elif / Else
- Other errors: AttributeError, FileNotFoundError, IndexError, KeyError, ModuleNotFoundError, NameError, RecursionError, SyntaxError, TypeError, UnboundLocalError, ValueError, ZeroDivisionError