[Solved] : IndentationError: unexpected indent in Python


Base class of IndentationError is SyntaxError. This exception occurred in Python because of incorrect Indentation because Python don’t use curly brackets for segregate blocks for loop, if-else, functions etc. it’s identify the blocks based on indentation only. Sometime if with in same block there is difference in indentations then it can throw TabError.

Note: Syntax error should not be handle through exception handling it should be fixed in your code.

You can check complete list of built-in exception hierarchy by following link. Python: Built-in Exceptions Hierarchy

Example

Here is simple example of reading the csv file by Python csv module. It’s throwing indentation error because of not proper indentation in second statement.

import csv
   with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record)

Output

File “C:/Users/saurabh.gupta14/Desktop/Python Example/ReadingCSV.py”, line 2
with open(‘C:\Users\saurabh.gupta14\Desktop\Python Example’,’r’) as csvfile:
^
IndentationError: unexpected indent

Solution

In the above example the second line is start from after taking tab which is not required. It should start without taking any space or tab. To fixed this issue i have remove the space and run it again.

import csv
with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record) 

The above modified code with not throw the IndentationError.

Learn Python exception handling in more detain in topic Python: Exception Handling

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s