[Solution]: Python IndentationError: Unexpected Indent In Python

SyntaxError is an error that can’t be resolved with the exception. We have to correct this error in our code. The base class of Python IndentationError is a syntax error. Python language doesn’t use curly braces to create blocks of code. By using indentation, we tell the compiler about separate code blocks. This error occurs when we use extra space, unnecessary extra lines, or multiple extra spaces. Sometimes you will see an error TabError. Python through this error if you use different indentation in the same code block. 

It is much easier to avoid these errors by using python formatting tools as discussed in dev.to. These formatting tools will automatically resolve indentation errors or notify you to resolve those. You can use es-lint, prettier, or many other plugins in vs code for this purpose.

Let’s move to an example where we can discuss Python IndentationError in more detail and how to solve this issue.

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

In the above example, there will be an error on line 2 as we add the wrong indentation there. Extra space will throw an IndentationError. Here is the output of this program. 

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

Python IndentationError Solution

We have successfully generated the error but how to resolve Python IndentationError? As we have discussed that we can’t solve this error with the exception or any other method. Read more about exception handling here. Now we need to remove the extra space from Line 2 and this Python IndentationError will be resolved. Here is the solved code. 

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

With the above code there will be no errors in output as we have resolved the issue of indentation.

Conclusion

I hope I have explained everything about indentation. Here are the simple instruction to avoid Python IndentationError.
1. Don’t add extra spaces.
2. Don’t add extra lines.
3. Install formatting tools like prettier/es-lint.

Let Us Know Your Feedback
+1
0
+1
0
+1
0
+1
0

Leave a Comment

Your email address will not be published.