How to Fix IndentationError: unexpected indent in Python
In this tutorial, you'll learn about How to Fix IndentationError: unexpected indent in Python. We cover key concepts, practical examples, and best practices.
Python raises IndentationError: unexpected indent when a line has extra whitespace at the start that does not match the expected indentation level of the surrounding block.
The Wrong Way
def greet(name):
print("Hello")
print("Welcome") # extra space before this line
This produces:
File "script.py", line 3
print("Welcome")
^
IndentationError: unexpected indent
The Right Way
Use consistent indentation (4 spaces per level) throughout the file:
def greet(name):
print("Hello")
print("Welcome")
Output:
Hello
Welcome
Step-by-Step Fix
1. Reveal invisible whitespace
Run cat to show tabs as ^I:
cat -A script.py
You will see ^I for tab characters and $ at line endings.
2. Convert tabs to spaces
Replace all tabs with 4 spaces:
expand -t 4 script.py > fixed.py && mv fixed.py script.py
3. Use a formatter
Auto-format with Black:
pip install black
black script.py
4. Configure your editor
Set VS Code to use spaces for indentation:
{
"editor.insertSpaces": true,
"editor.tabSize": 4,
"files.trimTrailingWhitespace": true
}
Prevention Tips
- Enable
editor.renderWhitespacein VS Code to see tabs and spaces. - Add Black or autopep8 to your pre-commit hooks.
- Use a
.editorconfigfile to enforce consistent indentation across the team. - Run
python3 -t script.pyin CI to catch tab-space mixing early. - Never copy-paste code from web pages into your editor without re-indenting.
Common Mistakes with indentation error
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro