Skip to content

How to Fix Python IndentationError

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix Python IndentationError. We cover key concepts, practical examples, and best practices.

The Problem

You run a Python script and get:

  File "script.py", line 5
    print("Hello")
    ^
IndentationError: expected an indented block after 'if' statement on line 4

Or:

  File "script.py", line 10
    return result
    ^
TabError: inconsistent use of tabs and spaces in indentation

Python uses indentation to define code blocks. Mixing tabs with spaces or using the wrong indentation level causes these errors.

Quick Fix

Step 1: Identify the exact line

The error message includes the file name and line number. Open that file and look at the indentation on the reported line and the line before it.

Step 2: Convert tabs to spaces

Run Python with the -t flag to check for inconsistent indentation:

python3 -t script.py

Use expand to convert tabs to spaces:

expand -t 4 script.py > fixed_script.py
mv fixed_script.py script.py

Step 3: Fix indentation level

Make sure all blocks at the same level have the same indentation:

# Wrong
if x > 0:
    print("Positive")
   print("Always runs")  # this line has 3 spaces instead of 4

# Right
if x > 0:
    print("Positive")
    print("Always runs")

Step 4: Re-indent with an editor

Use a code editor to fix indentation automatically:

# VS Code: Format Document (Shift+Alt+F)
# Or use autopep8
pip install autopep8
autopep8 --in-place script.py

Alternative Solutions

Use black to auto-format your entire file:

pip install black
black script.py

Black reformats everything to a consistent 4-space indentation.

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Prevention

  • Configure your editor to use 4 spaces instead of tabs.
  • Enable editor.renderWhitespace in VS Code to see invisible characters.
  • Add -t flag to your Python interpreter in CI to catch tab errors.
  • Run black or autopep8 before committing code.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro