Rectify an Unexpected Indent Error in Python

Rectify an Unexpected Indent Error in Python

Python is a programming language that relies a lot on spacing. Proper spacing and indentation are essential in Python for the program to work without errors. Spacing or indentation in Python indicates a block of code.

In this article, you’ll learn how to rectify the unexpected indent error in Python.

Rectify the IndentationError: unexpected indent Error in Python

An unexpected indent occurs when we add an unnecessary space or tab in a line of the code block. The message IndentationError: unexpected indent is shown when we run the code if this type of error is contained within your program.

The following code below shows an example of when an unexpected indent error occurs.

def ex1():
    print("Hello Internet")
        print("It's me")
ex1()

Output:

File "<string>", line 3
    print("It's me")
    ^
IndentationError: unexpected indent

In the example code above, we define a function ex1(), which contains two print statements. However, the second print statement has an unnecessary space or tab before it.

This code produces an unexpected indent error in line 3 as it encounters the additional space before the print("It's me") statement.

The following code rectifies the error contained in the previous program.

def ex1():
    print("Hello Internet")
    print("It's me")
ex1()

Output:

Hello Internet
It's me

Python is a programming language that strictly enforces indentation. Indentation also increases the readability of the code.

Indentation can be done in Python using either spaces or the tab button; choosing which one depends entirely on the user. The Python code needs to be indented in some cases where one part of the code needs to be written in a block.

Some cases where we need to use indentation and might get an unexpected indent error if we don’t do that are:

  • The if-else conditional statement
  • A for or a while loop
  • A simple function statement
  • A try...except statement

Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10