IndentationError: unexpected indent – Python

If you are learning Python, you may have seen this error:

IndentationError: unexpected indent

Unlike many other languages, indentation is part of Python syntax.
This error appears when Python finds spaces or tabs where it does not expect them.

Let’s understand this in the simplest way.


What Does This Error Mean?

Python found extra spaces or tabs at the beginning of a line where they are not allowed.

In Python, indentation must follow strict rules.
You cannot add random spaces like in Java or JavaScript.


❌ Example 1 – Extra Space at the Start

 print("Hello World")

Output

IndentationError: unexpected indent

✅ Fix

Remove the extra space:

print("Hello World")

❌ Example 2 – Indent Without a Block

name = "Alice"
print(name)

Python does not expect indentation after a normal statement.

✅ Fix

name = "Alice"
print(name)

❌ Example 3 – Mixing Tabs and Spaces

def show():
print("Hello") # tab
print("World") # spaces

Mixing tabs + spaces confuses Python.

✅ Fix

Use only spaces (recommended):

def show():
print("Hello")
print("World")

❌ Example 4 – Wrong Indentation Level

if True:
print("Hi")

Code inside if must be indented.

✅ Fix

if True:
print("Hi")

🧠 Why Python Is Strict About Indentation

In Python, indentation:

  • Defines code blocks
  • Replaces { } used in other languages
  • Makes code more readable

So Python treats wrong indentation as a syntax error.


✅ Simple Rules to Avoid This Error

  1. Do not add spaces at the beginning randomly
  2. Indent only after:
    • if, for, while, def, class, try
  3. Use either spaces OR tabs — never both
  4. Recommended: use 4 spaces per indent

🛠 Best Practice in VS Code / Editors

  • Enable: Convert tabs to spaces
  • Set indentation to 4 spaces
  • Turn on: Show whitespace

🎯 Interview One-Liner

IndentationError: unexpected indent occurs when Python finds indentation at a place where it is not syntactically allowed.


✨ Final Thought

Python is basically saying:

“I didn’t ask for indentation here!”

Fix the spaces → error gone 🚀