Online Tutorials & Training Materials | STechies.com
Register Login

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

09 Aug 2019 12:35 pm || 0

What is Indentation in Python?

In Python, indentation is the space or tab that programmers put at the beginning of every line. Indentation is important for making the 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. 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 whether it one space, two space and so on for the first line, it must be same for the rest of the lines. An error will occur if you don't follow the proper indentation.

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

What is Indentation

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 additional indent 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 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")