IndentationError: unindent does not match any outer indentation level
IndentationError: unindent does not match any outer indentation level in Python means a line moved back to the left, but not to a position any earlier block used. Python cannot tell which block the line belongs to.
How do I fix IndentationError: unindent does not match any outer indentation level?
IndentationError: unindent does not match any outer indentation level means a line moved left, but not to a column any earlier block uses. For example, the if uses 4 spaces but its else uses 2. Line the line up exactly with the block it belongs to. Mixed tabs and spaces cause the same error, so use 4 spaces everywhere.
- 1. Find the matching blockDecide which if, for or def the line belongs to. It must start in exactly that line's column.
- 2. Show whitespaceTurn on render whitespace in your editor. Tabs show as arrows, so a mixed line is easy to spot.
- 3. Convert to spacesRun your editor's Convert indentation to spaces command on the whole file, then re-check the reported line.
What does IndentationError: unindent does not match any outer indentation level mean?
When you finish a block, the next line must line up exactly with an earlier line, such as the if or def that opened the block. If the body uses 8 spaces and the line after it uses 2, there is no block at 2 spaces to go back to, so Python gives up. Mixed tabs and spaces cause the same thing even when the code looks lined up.
Why does IndentationError: unindent does not match any outer indentation level happen?
1. Dedenting to the wrong number of spaces
The else here has 2 spaces, but the if it belongs to has 4. Nothing else starts at 2.
Breaks
def check(n):
if n > 0:
return "positive"
else:
return "not positive"Works
def check(n):
if n > 0:
return "positive"
else:
return "not positive"2. Tabs and spaces that look the same
One line uses a tab, another uses spaces. They look aligned in your editor but Python counts them differently.
Breaks
for n in nums:
if n > 0:
print(n)
print("done") # 4 spacesWorks
for n in nums:
if n > 0:
print(n)
print("done")3. Mixing code with 2-space and 4-space indents
Pasting a snippet that uses 2 spaces into a file that uses 4 leaves lines that match nothing.
Breaks
def greet(name):
msg = "Hi " + name
return msgWorks
def greet(name):
msg = "Hi " + name
return msgHow to find it in your own code
Checklist: 1) Go to the line in the message and find the block it should belong to. 2) Make it start in exactly the same column as that block's other lines. 3) Turn on "show whitespace" in your editor to spot tabs. 4) Use 4 spaces everywhere; most editors can convert a whole file with "Convert indentation to spaces".
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.