Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Python

Python IndentationError: unindent does not match any outer indentation level

· 9 min read

Your loop prints three numbers. You add a line after it, run the program, and Python refuses to start:

Terminal
  File "main.py", line 3
    print("done")
                 ^
IndentationError: unindent does not match any outer indentation level

IndentationError: unindent does not match any outer indentation level means a line moved left (that's the "unindent"), but it stopped at a position where no block starts. Python can only go back to an indentation level it has already seen: the left edge, or the start of one of the blocks around this line. Here, print("done") is indented by two spaces, but the blocks above it use zero and four, so Python can't tell which block the line belongs to. The fix is to move it to one of those levels. This article shows how to find the right one, and the hidden tab that causes this error when everything looks perfectly lined up.

Try it yourself

Save this as main.py and run python main.py:

main.py
for n in range(3):
    print(n)
  print("done")

You'll get the error above. Python found it while reading the file, so nothing runs, not even the loop.

What the error means

In Python, indentation shows which lines belong together. Each time a line ends with a colon, the next lines move right and form a block. When the block ends, the next line moves back left, to the level of the code before the block.

Python keeps a list of the levels that are "open". In the example, the open levels are:

  • 0 spaces: the for line, at the left edge.
  • 4 spaces: the body of the loop.

A line can stay at 4 (still inside the loop) or go back to 0 (after the loop). Two spaces is neither, so Python stops.

Read the message in parts:

  • File "main.py", line 3: the line that moved back to a level that doesn't exist.
  • unindent: the line is further left than the one above it.
  • does not match any outer indentation level: no surrounding block starts at that position.

Then ask: should this line be inside the block above, or after it? The answer tells you whether to add spaces or remove them.

Cause 1: a line that went back only part of the way

The example above. You meant print("done") to run once, after the loop. Move it to the left edge:

main.py
for n in range(3):
    print(n)
print("done")
Terminal
0
1
2
done

If you meant it to run in every pass of the loop, move it right to four spaces instead, lined up with print(n).

Cause 2: a return that doesn't line up

The same happens at the end of a function, when the return is one space short:

main.py
def total(prices):
    result = 0
    for p in prices:
        result += p
   return result

print(total([4, 6]))
Terminal
  File "main.py", line 5
    return result
                 ^
IndentationError: unindent does not match any outer indentation level

The return has three spaces. The open levels are 0 (the def), 4 (the function body) and 8 (the loop body). The return belongs in the function body, after the loop, so it needs exactly four spaces, the same as result = 0.

One space is very hard to see. That's why turning on visible whitespace in your editor helps so much (see "How to see the spaces" below).

Cause 3: a block that started too far right

Sometimes the problem is the line above. Here the print inside the if has eight spaces instead of four:

main.py
score = 72
if score >= 50:
        print("pass")
    print("well done")
Terminal
  File "main.py", line 4
    print("well done")
                      ^
IndentationError: unindent does not match any outer indentation level

Python opened the if block at eight spaces, because that's where its first line started. Then print("well done") moved back to four, a level that was never opened. Python reports line 4, but the real mistake is line 3. Fix the first line of the block, so the block uses four spaces, and both lines line up.

So when the line Python names looks correct, look one or two lines up: was the block above started at an unusual position?

Cause 4: a method in a class

Classes add one more level, so the numbers get bigger, and the mistake is easier to make:

main.py
class Dog:
    def __init__(self, name):
        self.name = name

  def bark(self):
        print("Woof")
Terminal
  File "main.py", line 5
    def bark(self):
                   ^
IndentationError: unindent does not match any outer indentation level

Every method of a class must start at the same level as the first one, four spaces here. def bark has two. Move it to four, and keep its body at eight.

Cause 5: else or elif out of line

else and elif must line up exactly with their if:

python
x = 1
if x:
    print("a")
  else:
    print("b")
Terminal
  File "main.py", line 4
    else:
         ^
IndentationError: unindent does not match any outer indentation level

The else has two spaces; the if has none. Move else: to the left edge. The same rule applies to except and finally with their try.

The hidden cause: a tab among spaces

This is the version that drives people crazy: in your editor, every line looks perfectly aligned, and Python still complains. The reason is usually a tab character among lines indented with spaces. A tab and four spaces can look the same on screen, but they aren't the same characters.

Python 3 notices most of these and reports them as their own error:

Terminal
  File "main.py", line 3
    	print("there")
    ^
TabError: inconsistent use of tabs and spaces in indentation

But depending on where the tab sits, you can also get unindent does not match instead. Either way, the fix is the same: replace tabs with spaces.

Python can tell you which line has the problem. Run this in your terminal, in the folder with your file:

Output
python -m tabnanny main.py

In our test, it printed the file name, the line number and the line itself: d5.py 3 '\tprint("there")'. The \t is the tab.

How to see the spaces

You can't fix what you can't see. Make whitespace visible:

  • VS Code: Settings, search for "Render Whitespace", and set it to "all". Spaces show as dots, tabs as arrows.
  • Convert all tabs at once: in VS Code, open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and run "Convert Indentation to Spaces".
  • Make Tab insert spaces: most editors have an "insert spaces" setting. With it on, pressing Tab always gives four spaces, the standard from PEP 8.

Once you see the dots, a line with three or five spaces stands out immediately.

Errors that look alike

  • IndentationError: unexpected indent: the opposite direction, a line moved right without a reason. See unexpected indent.
  • IndentationError: expected an indented block: a line ended with a colon, but the next line isn't indented. See expected an indented block.
  • TabError: inconsistent use of tabs and spaces in indentation: tabs and spaces mixed in one block.
  • No error, wrong result: a line at the wrong valid level, for example inside a loop instead of after it. Python can't catch that one. Run your code and check that each line runs as often as you expect.

The same error in older Python versions

The message is the same in Python 3.8 and in current versions. In our test, Python 3.8 reported the same line with the same wording, IndentationError: unindent does not match any outer indentation level.

Wrong fixes that don't help

  • Adding or removing spaces until it runs. A line can end up in the wrong block, which runs without an error but gives a wrong result.
  • Re-indenting only the line Python names. If the block above started at an odd position (cause 3), fix that block, not only this line.
  • Retyping the whole file. Turn on visible whitespace instead: it takes seconds.

A debugging walkthrough

  1. Go to the line number in the message and turn on visible whitespace.
  2. Count the spaces on that line.
  3. Count the spaces on the lines that start each surrounding block: the def, for, if or class lines, and the first line inside each.
  4. Decide where the line belongs: inside the block above, or after it. Give it exactly that number of spaces.
  5. If the counts look right, look for a tab: run python -m tabnanny main.py, or convert indentation to spaces.

Practice

Predict what happens.

  1. A def at 0 spaces, its body at 4, and a return at 2.
  2. An if at 0, its body at 4, then an else: at 0.
  3. An if at 0, its first body line at 2, its second body line at 4.

Answers. (1) unindent does not match any outer indentation level: 2 is neither 0 nor 4. (2) No error: else lines up with if. (3) unexpected indent on the second body line: the block was opened at 2, and 4 is further right without a colon above it.

Frequently asked questions

What does "unindent does not match any outer indentation level" mean?

A line moved left, but not to a position where a surrounding block starts. Move it to the same level as the block it belongs to.

Why do I get this error when the code looks aligned?

There's probably a tab among spaces. Turn on visible whitespace, or run python -m tabnanny on the file.

How do I fix indentation in VS Code?

Turn on "Render Whitespace", then run "Convert Indentation to Spaces" from the Command Palette. Use Shift+Tab to move selected lines left.

How many spaces should I use?

Four per level. Python accepts other numbers, but every line in a block must use the same amount, and four is the standard.

Is this a syntax error?

Yes. IndentationError is a kind of SyntaxError, which is why it appears before your program runs.

A quick checklist

  1. Turn on visible whitespace.
  2. Count the spaces on the line Python names.
  3. Compare with the lines that open each surrounding block.
  4. Move the line to the level of the block it belongs to.
  5. Still stuck? Look for a tab with python -m tabnanny.

For a method that works on any error, read how to read an error message. The Python reference on indentation explains exactly how Python tracks the levels.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right