Register Login

Unindent does not match any outer indentation level: How to Fix this in Python:

Updated Oct 29, 2020

Indentation is important for making your code look well-structured and clean. This will help you to separate the code into multiple blocks and make it more readable. In languages such as C or C++, curly braces {} are used.

Improper indentation in Python raises an error called “unindent does not match any outer indentation level”. In this post, we will figure out the ways to solve this problem.

But first, let us learn about indentation in Python.      

What is Indentation in Python?

In Python, indentation is the space or tab that programmers put at the beginning of every line. In Python, whitespace is used for indenting the code. Code is indented from left to right.

In python, we don't use indention just for the beautification of code or to make the code look pretty. When you do indent using one space or two space for the first line, it must be same for the rest of the lines. 

In the picture shown below, you can see there are three blocks of code, and each block code has an identical indentation. 

What is Indentation

What is 'IndentationError: unindent does not match any outer indentation level'?

This type of error occurs when we assign extra indent to an identical code block. Due to this additional indent, the python compiler is not able to recognize similar code blocks, and it throws an error. To fix this, you have to make sure all blocks of similar code have the same indentation.

IndentationError: Unindent does not match any outer indentation level

Let us look at some examples to understand the error and its solution.

Example:

a = int(input("Please enter an integer A: "))
b = int(input("Please enter an integer B: "))
if b > a:
        print("B is greater than A")
elif a == b:
        print("A and B are equal")
    else:
        print("A is greater than B"

Output:

File "t.py", line 7
    else:
        ^
IndentationError: unindent does not match any outer indentation level

In the above code example “if” and “elif” statements are assigned with no indent whereas “else” statement (see line no 7) which is belong to “if” statement, assigned with an extra indent. Due to an additional indent python compiler was not able to recognize “else” statement (line no 7) and throw the indentation error ’unindent does not match any outer indentation level’.

Correct Code:

a = int(input("Please enter an integer A: "))
b = int(input("Please enter an integer B: "))
if b > a:
        print("B is greater than A")
elif a == b:
        print("A and B are equal")
else:
        print("A is greater than B")

Therefore, before compiling the code, check the overall indentation to avoid the “unindent does not match any outer indentation level” error. 


×