Python doesn’t mess around when it comes to indentation. If your code has even one line that’s indented more than expected, Python will throw an IndentationError. Let’s look at why this happens, how to fix it, and how to avoid it in future projects.

What the Error Looks Like

Here’s a typical example:

This error shows up when you run your Python script and see something like:

def say_hello(): print("Hello") print("World") # <- Unexpected indent

Why This Error Happens

Python uses indentation to define code blocks, unlike many other languages that use curly braces ({}).

Python shows this error when there’s an extra space or tab where it shouldn’t be.

Common reasons:

  • A line starts with a space or tab by mistake
  • Adding tabs and spaces in the same file

Steps to Fix the Error

Step 1: Check for Inconsistent Indentation

All statements within a block (like inside a function or if statement) should be indented at the same level.

def greet(): print("Hi") # Correct print("there") # ❌ Incorrect -- unexpected indent

Fix:

def greet(): print("Hi") print("there")

Step 2: Avoid Mixing Tabs and Spaces

Some editors insert spaces; others insert tabs. Mixing both in the same file causes indentation errors.

Use this to convert tabs to spaces (recommended):

# In VSCode, enable:
# "Insert Spaces" instead of "Keep Tabs"

Or use this Python tool:

autopep8 yourfile.py --in-place

Step 3: Use a Linter or Code Formatter

Install tools like:

  • Flake8
  • black
  • autopep8

These can detect and fix indentation issues automatically.

Summary

IndentationError: unexpected indent means your code’s structure is off and Python can’t interpret it. The best way to avoid this is to stick with 4-space indentation, avoid mixing tabs and spaces, and use an editor that highlights formatting issues. If your project has growing complexity or collaborative code, it’s worth it to hire Python developers who follow clean formatting practices and prevent errors like this before they happen.