IndentationError: unindent does not match any outer indentation level
What it means
When a line moves back to the left, it must land exactly in the column of an earlier, outer block. Python found a line that sits between two levels, for example 2 spaces in when the lines around it use 0 and 4. Python cannot tell which block that line belongs to.
1. A `return` that does not line up with the function body
This raises the error
Broken
def total(prices):
result = 0
for p in prices:
result += p
return result
print(total([3, 4, 5]))
Output
Traceback (most recent call last):
File "<exec>", line 5
return result
^
IndentationError: unindent does not match any outer indentation levelThe fix
Fixed
def total(prices):
result = 0
for p in prices:
result += p
return result # 4 spaces, the same as result = 0
print(total([3, 4, 5]))
Output
12
The return belongs to the function body, which starts 4 spaces in. At exactly 4 spaces it lines up with result = 0 and Python knows where it belongs.
2. An `else` that does not line up with its `if`
This raises the error
Broken
score = 72
if score >= 50:
print("Pass")
else:
print("Fail")
Output
Traceback (most recent call last):
File "<exec>", line 4
else:
^
IndentationError: unindent does not match any outer indentation levelThe fix
Fixed
score = 72
if score >= 50:
print("Pass")
else:
print("Fail")
Output
Pass
else must start in exactly the same column as the if it belongs to.
When you see this error, check
- Check the column of the line Python points to against the blocks above it.
- Stick to 4 spaces per level. Mixing 2 spaces in one place and 4 in another causes this error.
- Re-indent lines you copied from somewhere else so they match the code around them.
- If the columns look right and the error stays, a tab may be hiding among the spaces. Delete the indent and retype it with spaces.
Related errors
All Python errors · How to read a traceback · Step through your code