What This Error Means
When running a Python script, you may hit the following error:
File "script.py", line 3
print("Welcome to Python!")
^
IndentationError: unexpected indentIndentationError: 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 spaceThe usual causes are:
- Tabs and spaces are mixed in the same file.
- A line is indented where no indentation is expected.
- Lines in the same block use different indentation widths.
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.pyIf 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:
- Open File > Preferences > Settings.
- Set "Editor: Tab Size" to
4. - 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.py4. 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 blockCorrected:
if True:
print("This is correct.")Summary
IndentationError: unexpected indent is caused by Python's strict indentation rules. To resolve it:
- Unify indentation to 4 spaces and remove stray tabs.
- Configure your editor to insert spaces and show whitespace.
- Use a formatter such as Black to fix the whole file automatically.