πŸ”§ Error Fixes

Python IndentationError β€” How to Fix Unexpected Indent


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:

  1. Open the file
  2. Click β€œSpaces: 4” or β€œTab Size: 4” in the bottom status bar
  3. 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