Error Encyclopedia

IndentationError: unexpected indent

Fix 'IndentationError: unexpected indent' in Python. Learn Python's indentation rules and how to fix spacing issues.

What Does This Error Mean?

The 'IndentationError: unexpected indent' error means Python encountered a line with indentation that does not match the expected block structure. Python uses indentation (whitespace at the start of lines) to define code blocks — unlike many languages that use braces or keywords.

Common Causes

1

Mixing tabs and spaces in the same file

2

Extra spaces before a line that should not be indented

3

Missing or extra indentation in a code block

4

Editor configured to use tabs while the project uses spaces (or vice versa)

5

Copying code from a web page that introduced inconsistent whitespace

6

Indentation level mismatch between an if/for/def and its body

How to Fix It

Use consistent indentation (4 spaces)

PEP 8 recommends 4 spaces per indentation level. Configure your editor to use spaces.

# ✅ Correct indentation with 4 spaces
def greet(name):
    if name:
        print(f"Hello, {name}")
    else:
        print("Hello, World")

# ❌ Mixed tabs and spaces
def greet(name):
	if name:
        print(f"Hello, {name}")  # Tab then spaces → Error

Reveal whitespace in your editor

Enable visible whitespace to see if tabs and spaces are mixed.

# VS Code: Ctrl+Shift+P → "Toggle Render Whitespace"
# Or add to settings.json:
"editor.renderWhitespace": "all"

# Find tabs in your file with Python
python -c "print(repr(open('file.py').read()))" | findstr \\t

Convert tabs to spaces

Use an automated tool to fix inconsistent indentation.

# Use autopep8 to fix indentation
pip install autopep8
autopep8 --in-place file.py

# Or use Python's own tabnanny for checking
python -m tabnanny file.py

# VS Code: Format Document (Shift+Alt+F)
# Or use "editor.formatOnSave": true

Before & After Examples

❌ Before
def calculate_total(items):
    total = 0
    for item in items:
        total += item.price
      return total  # ❌ Wrong indentation level
✅ After
def calculate_total(items):
    total = 0
    for item in items:
        total += item.price
    return total  # ✅ Correct indentation (back to for level)

Related Errors

Other common errors in this category:

Frequently Asked Questions

Should I use tabs or spaces in Python?

PEP 8 (Python's style guide) recommends 4 spaces per indentation level. Most Python projects use spaces. Configure your editor to insert spaces when you press Tab.

How do I fix mixed tabs and spaces in an entire project?

Use `autopep8 --in-place --aggressive --aggressive **/*.py` or `black .` to auto-format your entire project. Use `python -m tabnanny *.py` to find files with inconsistent indentation.