Public

How to Fix "IndentationError: unexpected indent" in Python

This article contains ads and affiliate links.

Python Python
t-salad t-salad committed 4c5e099

What This Error Means

When running a Python script, you may hit the following error:

Sponsored Links
File "script.py", line 3
    print("Welcome to Python!")
    ^
IndentationError: unexpected indent

IndentationError: unexpected indent means a line starts with more whitespace than Python expected at that point. Python uses indentation to define code blocks, so an extra space or tab at the beginning of a line is a syntax error, not just a style issue.

A minimal example that triggers it:

def greet():
    print("Hello, world!")
     print("Welcome to Python!")  # one extra space

The usual causes are:

  1. Tabs and spaces are mixed in the same file.
  2. A line is indented where no indentation is expected.
  3. Lines in the same block use different indentation widths.
Sponsored Links

How to Fix It

1. Make the indentation consistent

The recommended style in Python is 4 spaces per indentation level. The corrected version of the example above:

def greet():
    print("Hello, world!")
    print("Welcome to Python!")

To check whether the file contains tab characters, run:

grep -P "\t" script.py

If any lines are printed, replace the tabs with spaces.

2. Configure your editor

Set your editor to insert spaces automatically so the problem does not come back. In Visual Studio Code:

  1. Open File > Preferences > Settings.
  2. Set "Editor: Tab Size" to 4.
  3. Enable "Insert Spaces" (inserts spaces instead of tab characters).

Enabling "Render Whitespace" also helps: it makes stray tabs and spaces visible at a glance.

3. Auto-format the file

A formatter fixes indentation across the whole file in one step. With Black:

pip install black
black script.py

4. Check for related indentation errors

If the error persists, the file may contain a different indentation problem, such as a missing indent after a colon:

if True:
print("This is incorrect.")  # expected an indented block

Corrected:

if True:
    print("This is correct.")

Summary

IndentationError: unexpected indent is caused by Python's strict indentation rules. To resolve it:

  1. Unify indentation to 4 spaces and remove stray tabs.
  2. Configure your editor to insert spaces and show whitespace.
  3. Use a formatter such as Black to fix the whole file automatically.

References

Sponsored Links
Sponsored Links
★ Share on X
Related posts