As we all know, error messages are a fundamental part of the coding experience. However, some result more from how your code is formatted than the code itself- especially in the Python programming language. Indentations are one of the most important parts of Python formatting, and any tiny slip up can result in an error message such as this one.
What exactly is it?
Indentationerror: unindent does not match any outer indentation level is an interesting one, because it can be hard to find in your code. Being a python indentation error, it has to do with the fact that both tabs and whitespaces are used for python indentation. On your screen, the python indentation created by the tab key and a whitespace look practically identical, though functionally they are different. This is why this improper indentation error results from your code block, and why creating an indented block with correct indentation is extremely challenging.
How does it happen?
In python, a proper indentation can be done with either the tab key or a whitespace- it does not matter which one you use, so long as you are consistent. Python code with an internal indentation level that doesn’t match the outer indentation level will cause a mixed tab, inconsistent indentation, and similar error messages to this one. Oftentimes this problem occurs when you paste a function into your python program from elsewhere, causing the inconsistent indentation. However, similar error messages will occur anytime there is not 100% agreement between the indentation types.
How do I fix it?
Fixing indentationerror: unindent does not match any outer indentation level error is fairly straightforward once you can find it. One way to find the wrong indentation is by loading the code example into a text editor such as sublime text. Sublime text will show you the tab and space differences, allowing you to identify the error and inconsistencies in your indentation. In the future, make sure to indent your code consistently, only using the tab key for example, never mixing them.
This is an easy mistake to make, but once you can find the indentation problem among all the indented code blocks in your code editor, it is very easy to find. And from here on out, by using the same key for all of your indented code blocks you can avoid similar error messages to this one, and stop this indentation problem before it happens.