🔧 Error Fixes
· 2 min read
Last updated on

Python IndentationError — How to Fix It


IndentationError: unexpected indent

What causes this

Python uses indentation to define code blocks (unlike most languages that use braces {}). This error means Python found indentation where it didn’t expect it, or the indentation is inconsistent. The three main causes:

  • Mixing tabs and spaces in the same file
  • Inconsistent indentation levels (3 spaces in one place, 4 in another)
  • Extra indentation on a line that shouldn’t be indented

Fix 1: Find the mixed tabs and spaces

This is the most common cause. Tabs and spaces look the same but Python treats them differently:

# ❌ Mixed tabs and spaces (invisible difference)
def greet():
	name = "Alice"  # this line uses a tab
    print(name)     # this line uses spaces — IndentationError!

# ✅ Use 4 spaces everywhere
def greet():
    name = "Alice"
    print(name)

Use Python’s built-in checker to find the problem:

python -m tabnanny script.py

This will tell you exactly which lines have mixed indentation.

Fix 2: Configure your editor to use spaces

Set your editor to insert spaces when you press Tab:

VS Code — add to settings.json:

{
  "editor.insertSpaces": true,
  "editor.tabSize": 4,
  "editor.detectIndentation": false,
  "[python]": {
    "editor.tabSize": 4
  }
}

PyCharm: Settings → Editor → Code Style → Python → uncheck “Use tab character”

Vim: add to .vimrc:

set expandtab
set tabstop=4
set shiftwidth=4

Fix 3: Fix an extra indent

Sometimes a line is just indented too much:

# ❌ Extra indent on the return statement
def add(a, b):
    result = a + b
        return result  # IndentationError!

# ✅ Same level as the rest of the function body
def add(a, b):
    result = a + b
    return result

Fix 4: Fix indentation after copy-paste

Pasting code from the web often introduces wrong indentation. Select the pasted block and re-indent it:

  • VS Code: Select the block, then Cmd+] / Ctrl+] to indent, Cmd+[ / Ctrl+[ to unindent
  • Or use the command palette: “Reindent Lines”

Fix 5: Convert the entire file

If the file is a mess, convert all indentation at once:

# Convert tabs to 4 spaces
expand -t 4 script.py > script_fixed.py
mv script_fixed.py script.py

Or in VS Code: open the command palette (Cmd+Shift+P) → “Convert Indentation to Spaces”

How to prevent it

  • Configure your editor to use spaces (4 spaces is the Python standard per PEP 8)
  • Add an .editorconfig file to your project so all contributors use the same settings
  • Use a linter like flake8 or ruff that catches indentation issues before you run the code
  • Never mix tabs and spaces — pick one and stick with it (spaces is the standard)
📘