[Solved] IndentationError: unexpected indent

IndentationError: unexpected indent

An IndentationError: unexpected indent occurs when Python encounters an unexpected level of indentation in your code. This error typically happens when there is an extra space or tab before a line where extra indentation is not expected.

For example, consider the following program, where we have a function named addition() that computes the sum of given arguments, and return the result. But, if you observe, the body of the function is not indented property. The first line in the function body has two spaces which is an acceptable indentation for the body of a function. But the return statement, instead of two spaces of indentation as that of previous line, has four spaces. This is unexpected.

Python Program

def addition(a, b):
  result = a + b
    return result

print(addition(10, 20))

Output

  File "example.py", line 3
    return result
IndentationError: unexpected indent

The message printed to the output clearly states that Python interpreter got an unexpected indent at line 3.

Solution

Let us correct the indentation for the statement at line 3.

Python Program

def addition(a, b):
  result = a + b
  return result

print(addition(10, 20))

Output

30

Now, the program has run without any IndentationError.

Summary

In this tutorial, we learned how to solve the IndentationError that occurs when we provide an inconsistent indentation for the statements inside a block of code.

Code copied to clipboard successfully 👍