How to 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 awhile
loop - A simple
function
statement - A
try...except
statement
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
LinkedInRelated Article - Python Error
- Can Only Concatenate List (Not Int) to List in Python
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python