Python IndentationError
Python code has inconsistent or incorrect indentation.
Explanation
IndentationError is a specific type of SyntaxError that occurs when Python encounters inconsistent indentation. Python uses indentation to define code blocks instead of curly braces. Mixing tabs and spaces, having inconsistent indentation levels, or missing indentation for code blocks will trigger this error. Python 3 disallows mixing tabs and spaces. Each indentation level should be consistent (typically 4 spaces).
Common Causes
- Mixing tabs and spaces
- Inconsistent indentation levels
- Missing indentation after control structure
- Editor not configured for Python
- Copy-pasting code with different indentation
Solution
Configure your editor to use 4 spaces for indentation and convert all tabs to spaces. Enable "show whitespace" in your editor to see indentation characters. Use autopep8 or black to automatically format Python code. Check that all code within blocks (if, for, while, def, class) is indented at the same level. Run black filename.py to auto-format the entire file.
Code Example
# Mixed tabs and spaces - IndentationError
def greet():
print("Hello") # 4 spaces
\tprint("World") # tab - ERROR!
# Fix: use consistent spaces
def greet():
print("Hello") # 4 spaces
print("World") # 4 spaces
# Missing indentation
def greet():
print("Hello") # no indentation - ERROR!
# Fix
def greet():
print("Hello")
# Auto-format with black
# pip install black
black script.py
Error Information
Language
python
Difficulty
Beginner
Views
10
Related Errors
Python
Python FileNotFoundError
The code tries to open or access a file or directory that does not exist.
Python
Python KeyError
The code tries to access a dictionary key that doesn't exist.
Python
Python AttributeError
The code tries to access an attribute or method that doesn't exist on an object.
Python
Python TypeError: argument of type is not iterable
The code tries to iterate over a value that is not iterable.