Python
Indentation
Programming Tips
Code Debugging
Python Errors

How to fix Python indentation

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python uses indentation as part of the language syntax, so indentation errors are not cosmetic. If a block is misaligned, Python may raise IndentationError, TabError, or run a different block structure than you intended.

What Correct Indentation Looks Like

Python groups code by indentation level. After statements such as if, for, while, def, class, and try, the following block must be indented consistently.

Correct example:

python
1def greet(name):
2    if name:
3        print(f"Hello, {name}")
4    else:
5        print("Hello")

Broken example:

python
def greet(name):
if name:
    print(f"Hello, {name}")

The second example fails because the if block is not indented under the function body.

The Fastest Way To Fix It

When Python shows an indentation error, start with the line in the traceback, then inspect the lines immediately above it. The actual mistake is often one line earlier.

A practical repair process is:

  1. identify which statement opened the block
  2. confirm every line in that block has the same indentation width
  3. check whether tabs and spaces were mixed
  4. reindent the whole block with spaces

Most editors can do this automatically once you select the broken lines.

Use Four Spaces And Avoid Tabs

PEP 8 recommends four spaces per indentation level. More importantly, pick one style and keep it consistent. In modern Python projects, that usually means spaces only.

This file mixes tabs and spaces and may fail:

python
def calculate():
	print("tab")
    print("spaces")

Fix it by converting indentation to spaces:

python
def calculate():
    print("tab converted to spaces")
    print("spaces")

If Python reports TabError: inconsistent use of tabs and spaces, this is the first thing to check.

Let Your Editor Help You

Good editors make indentation bugs much easier to spot. Turn on:

  • visible whitespace
  • automatic conversion of tabs to spaces
  • format on save
  • Python linting

For example, once black is installed, you can reformat a file with:

bash
black my_script.py

A formatter will not fix every logical mistake, but it will quickly normalize indentation where the code is already structurally valid.

Watch Out For Copy And Paste Problems

A lot of indentation bugs come from copying code between websites, terminals, editors, or email clients. Hidden tabs, nonstandard spaces, or pasted blocks from another nesting level can all cause trouble.

If a block looks correct but Python still complains, delete the leading whitespace on the affected lines and type it again manually. That often fixes invisible formatting issues faster than staring at the screen.

Indentation In Nested Blocks

Errors become easier to make as nesting grows:

python
1for user in users:
2    if user.is_active:
3        for order in user.orders:
4            print(order.id)

When one line in a nested block is off by even one level, Python changes the structure. Keeping functions short and avoiding unnecessary nesting reduces these mistakes.

A Simple Debugging Trick

If you are unsure where the structure broke, temporarily replace complex code with pass to rebuild the block layout:

python
1def process(items):
2    for item in items:
3        if item > 0:
4            pass

Once the skeleton is correctly indented, add the real statements back one block at a time.

Common Pitfalls

  • Mixing tabs and spaces in the same file or block.
  • Fixing only the line mentioned in the error instead of checking the surrounding block.
  • Copying code from a source that changed the leading whitespace characters.
  • Over-nesting code until the intended block structure becomes hard to see.
  • Relying on manual alignment without editor support or a formatter.

Summary

  • Indentation is part of Python syntax, not just style.
  • Use consistent four-space indentation and avoid tabs.
  • Check the line above the reported error as well as the reported line.
  • Use editor whitespace visualization, linting, and formatting tools to catch problems early.
  • If necessary, retype the leading whitespace or rebuild the block with pass before restoring the code.

Course illustration
Course illustration

All Rights Reserved.