IndentationError: unexpected indent
IndentationError: expected an indented block
TabError: inconsistent use of tabs and spaces in indentation
Python uses indentation to define code blocks (instead of curly braces). If the indentation is wrong, Python canβt parse your code.
Fix 1: Unexpected Indent
# β Extra indentation
def greet():
print("hello")
print("world") # π₯ unexpected indent
# β
Consistent indentation
def greet():
print("hello")
print("world")
Fix 2: Expected an Indented Block
# β Empty block
def greet():
# nothing here π₯
# β
Use pass for empty blocks
def greet():
pass
# β After if/for/while
if True:
print("hello") # π₯ needs to be indented
# β
if True:
print("hello")
Fix 3: Mixed Tabs and Spaces
The most annoying cause. Your file has both tabs and spaces, and they look the same.
# Show tabs vs spaces in your file
cat -A script.py
# Tabs show as ^I, spaces show as regular spaces
Fix in VS Code:
- Open the file
- Click βSpaces: 4β or βTab Size: 4β in the bottom status bar
- Select βConvert Indentation to Spacesβ
Fix from command line:
# Replace tabs with 4 spaces
expand -t 4 script.py > script_fixed.py
mv script_fixed.py script.py
Prevent it: Add to VS Code settings:
{
"editor.insertSpaces": true,
"editor.tabSize": 4,
"[python]": {
"editor.insertSpaces": true,
"editor.tabSize": 4
}
}
Fix 4: Copy-Pasted Code
Code copied from websites or PDFs often has invisible characters or wrong indentation.
Fix: Select all the indentation on the pasted lines and re-type it manually.
The Rule
- Use 4 spaces per indentation level (Python standard)
- Never mix tabs and spaces
- Configure your editor to insert spaces when you press Tab