The use of indentation for indicating blocks of code is a defining feature of Python that sets it apart from other programming languages. Without proper indentation, code can be  misinterpreted, leading to errors and bugs. Python, therefore,  enforces proper indentation in order for the interpreter to function and evaluate the code properly.  

IndentationError exception is raised when incorrect indentation is encountered. It is generally raised when the indentation of a statement is not in accordance with the prescribed syntax of the language such as when an inconsistent number of tabs and spaces are used.

IndentationError is a type of syntax error, it is actually implemented as a subclass of the SyntaxError exception.

IndentationError is derived from SyntaxError 

print(issubclass(IndentationError, SyntaxError))

 

There are mostly two variations of IndentationError:

  1. When we indent a statement of code where we are not supposed to.

a = 100
  b = 200
  1. When we fail to indent a statement when we are expected to  

def func():
print("Indentation error coming!!")
for i in range(10):
print(i)

Common causes of IndentationError

  • Mixing tabs and spaces- Tabs and spaces are both correct forms of indentation in Python. However, when we mix the two, the Interpreter gets confused between which of the two to use and  consequently raises an IndentationError exception.

  • Having an indentation in unexpected place.

  • Failing to consistently indent statements inside a block -  In Python, blocks of code are separated using indentation. If a programmer fails to indent statements inside a block, IndentationError will be raised.

  • Copying and pasting code from a source that uses different conventions for indentation.

Fixing IndentationError Exceptions

The best way to fix an IndentationError exception is to go through the code line-by-line and check for any inconsistencies in whitespace, tabs, or mixing of whitespace. Once the statement causing the error has been identified, the necessary changes can be made in order to resolve the error. 

Sometimes, however,  IndentationError exceptions are not that easy to locate especially in the case of mixing tabs with whitespace. This is because visually, the code looks correctly indented but the Python interpreter  interprets tabs and spaces differently. To avoid this issue, it is best to stick to one type of indentation (either tabs or spaces) from the start . But in the case where the error has already happened, you can find the settings option in your IDE or  text editor to automatically converts tabs to spaces and vice versa.