0
0
PythonDebug / FixBeginner · 3 min read

How to Fix Indentation Error in Python: Simple Steps

An IndentationError in Python happens when your code lines are not properly aligned using spaces or tabs. To fix it, make sure all blocks of code use consistent indentation, typically 4 spaces per level, and avoid mixing tabs and spaces.
🔍

Why This Happens

Python uses indentation (spaces or tabs at the start of a line) to group code together. If the indentation is inconsistent or missing where Python expects it, you get an IndentationError. This usually happens when mixing tabs and spaces or forgetting to indent after a statement like if or for.

python
if True:
    print("Hello")
Output
File "<stdin>", line 2 print("Hello") ^ IndentationError: expected an indented block
🔧

The Fix

To fix the error, indent the code inside the block consistently. Use 4 spaces per indentation level and do not mix tabs and spaces. This tells Python which lines belong together.

python
if True:
    print("Hello")
Output
Hello
🛡️

Prevention

Always use the same type of indentation (spaces recommended). Configure your code editor to insert spaces when you press Tab. Use a linter tool like flake8 or pylint to catch indentation issues early. Consistently indent blocks after statements like if, for, def, and while.

⚠️

Related Errors

Other common errors related to indentation include:

  • TabError: Occurs when tabs and spaces are mixed in indentation.
  • SyntaxError: Happens if indentation is missing or unexpected in places.

Fix these by using consistent indentation and checking your code structure.

Key Takeaways

IndentationError means Python expects consistent indentation to group code blocks.
Use 4 spaces per indentation level and never mix tabs with spaces.
Configure your editor to insert spaces when pressing Tab for consistency.
Use linters like flake8 or pylint to catch indentation problems early.
Indent all code inside blocks after statements like if, for, def, and while.