How to fix “Unindent does not match any outer indentation level” in Python

Updated Oct 23, 2023 ⤳ 7 min read

Python’s infamous “IndentationError: unindent does not match any outer indentation level” error occurs when the indentation of a line doesn’t match up with the expected indentation level of the current code block.

🎧 Debugging Jam

Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀

Here’s what the error looks like:


File /var/www/sandbox/test.py, line 4
  print(word)
        ^
IndentationError: unindent does not match any outer indentation level

In the above error message, Python complains about line 4, where the code is indented differently than what Python expects.

Copy/pasting code snippets from the Internet or another editor is the common can lead to improper indentation. 

Since the error message shows the exact location, the solution is just re-indenting the affected lines.

In this quick guide, I'll explain why this error happens and how indentation in Python works.

We'll finish the guide by learning tips on fixing indentation-related issues on three popular code editors. 

Indentation in Python Explained 

In Python, indentation isn't a style choice; It's a part of the syntax and is required by Python flow-control features such as if statements, loops, classes, and functions.

Python uses the whitespaces at the beginning of a line to compute the indentation level of that line; It's how Python figures out to which block the statement belongs.

For instance, it'll know which statements are inside the loop to be repeated.


word = 'example'
for letter in word:
    print(letter)
 print(word)

In the above example, Python considers the first print statement to be inside the loop and the second print statement to be outside.

Now, let's see when this indentation code occurs?

In the above example, if you indent the second print by a couple of whitespaces, you'd make an ambiguous situation for Python to determine the indentation level of our loop. 

Python expects the line following an indentation level (e.g., for) to be less indented. However, in our example, the second print statement is slightly indented to the right. This makes it the determining line for Python to compute the indentation level for our for loop.

And since the first print statement is now indented differently than the determining line, Python throws the "Unindent does not match any outer indentation level" error.


word = 'example'
for letter in word:
    print(letter)
 print(word)

Another example is an if/else statement:


if a==1:
    print('test')
 else:
    print('test2')

In the above code, else is slightly indented to the right. And since Python expects it to be at the same level as if, it throws the indentation error.

As a rule of thumb, statements ending with a colon (:) require the following line to be indented (a new indentation block).

The relevant statements are:

  • class
  • def (functions)
  • if, elif, and else
  • for and while
  • try, except, and finally
  • with
  • match and case (Python 3)

Evil tabs!

Sometimes all lines look perfectly aligned, but you still get the error. That usually happens when you copy a tab-indented code from the Internet:

You usually won't have to worry about it because most modern editors automatically convert tabs to spaces (or vice versa if configured accordingly). 

However, if you copy/paste a code snippet from the Internet (e.g., Stackoverflow), you'll have to re-indent them manually.

To avoid this situation, you can make all whitespaces visible in your code editor. This will give you a quick way to prevent (or debug) indentation-related mistakes.

Additionally, you can use Python's tabnanny module to help you detect indentation errors quickly. Tabnanny checks for consistency in the indentation of code blocks in a Python code. If such an error is detected, it will throw the indentation error.


dwd@dwd-sandbox:~$ python3 -m tabnanny test.py 
'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 4)

How to fix it?

As mentioned earlier, you can fix this indentation error by ensuring that the indentation of the code block matches the expected indentation level. 

But there are also automatic ways to do so. That's actually the preferred method among Python developers. Let me share with you some indentation tips & tricks on three popular code editors:

  1. Visual Studio Code
  2. Sublime Text
  3. Vim 

Visual Studio Code:  Firstly, to make whitespace characters (space or tab) visible in VS code, open up the command palette by pressing ⌘+Shift+P (on Mac) or Ctrl+Shift+P (on Windows), type, Toggle Render Whitespaces and hit enter (↵)

As a result, whitespaces are displayed as gray dots and tabs as tiny arrows. Having whitespaces visible enables you to spot inconsistencies as your write code - even if they look fine.

And to fix the possible tab/space inconsistencies, open up the command pallet again, and run "Convert Indentation to Spaces" or "Convert Indentation to Tabs" - depending on what character you use for indentation.

Sublime Text: If you have a space/tab indentation issue on Sublime Text, go to View -> Indentation and select Indent Using Spaces.

And to see the whitespace characters, highlight your code (Ctrl + A), and you should be able to see any possible inconsistency.

Vim:  Like the other editors, Vim automatically converts any whitespace to space characters. However, if you've copied some tab-indented code from elsewhere, you can use Vim's :retab command to convert them into spaces quickly.

You can make whitespace characters visible with set list and set listchars commands. 

First, run this in Vim:


:set list

And then run:


:set listchars=space:,tab:-> 

You can replace and -> with the characters of your choice.

A note on Tabs and space characters in Python indentation

In Python, tabs and spaces are interchangeable when it comes to indentation. 

However, the Python style guide (PEP 8) recommends using spaces over tabs - 4 space characters per indentation level.

According to PEP 8, if you're working with a code that's already using tabs, you can continue using them to keep the indentation consistent. 

Additionally, Python disallows mixing tabs and spaces for indentation. So you can't use tabs and space characters in the same indentation level - Just like the above examples.

Alright, I think that does it! I hope you found this quick guide helpful.

Thanks for reading.

Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.

`
Exit mobile version