Python IndentationError
In Python, an IndentationError
occurs when there is an issue with the indentation of your code.
Python uses indentation to define blocks of code, such as those within loops, conditionals, and function definitions.
Incorrect indentation can lead to IndentationError
.
In this tutorial, we will go through some of the common scenarios where IndentationError
might occur.
1. Incorrect indentation level
If the indentation of your code is inconsistent within a block (e.g., mixing tabs and spaces, or using the wrong number of spaces), Python will raise an IndentationError
.
Python Program
if True:
print("Indented code") # Incorrect indentation
Output
File "example.py", line 2
print("Indented code") # Incorrect indentation
^
IndentationError: expected an indented block after 'if' statement on line 1
2. Mixing tabs and spaces
Python requires consistent indentation throughout your code. Mixing tabs and spaces can lead to IndentationError
.
Python Program
if True:
print("Indented code")
print("Incorrect indentation") # Mixing tabs and spaces
Output
File "example.py", line 3
print("Incorrect indentation") # Mixing tabs and spaces
^
IndentationError: unindent does not match any outer indentation level
3. Unexpected indentation
If Python encounters unexpected indentation (e.g., extra spaces or tabs), it will raise an IndentationError
.
Python Program
def my_function():
print("Indented code")
print("Unexpected indentation") # Unexpected indentation
Output
File "example.py", line 3
print("Unexpected indentation") # Unexpected indentation
^
IndentationError: unindent does not match any outer indentation level
Solution
To resolve IndentationError
, ensure that your code is consistently indented using spaces (recommended) or tabs, but not a mixture of both.
Also, check for any extra or missing indentation within blocks of code. Most code editors support automatic indentation correction and highlighting, which can help you identify and fix indentation errors more easily.
More Tutorials on IndentationError
The following tutorials cover some of the scenarios where we encounter IndentationError, and also the solutions to fix the IndentationError for each case.
- [Solved] IndentationError: expected an indented block after 'if' statement
- [Solved] IndentationError: expected an indented block after 'for' statement
- [Solved] IndentationError: expected an indented block after function definition
- [Solved] IndentationError: unexpected unindent
- [Solved] IndentationError: unindent does not match any outer indentation level
Summary
In this tutorial, we learned about IndentationError
, some of the common scenarios that can trigger this error, and how to solve this error, with examples.