IndentationError: unexpected indent
Quick summary
Your code has inconsistent indentation — Python uses indentation to define blocks and raises IndentationError when spaces do not align.
Why this happens
You mixed tabs and spaces for indentation, or used a different number of spaces than the surrounding block
A line was accidentally indented or dedented, breaking the expected block nesting level
You copied code from another source with different indentation settings (2-space vs 4-space)
Minimal example
def greet(name):
print('Hello')
print('World') # unexpected indent
returndef greet(name):
print('Hello')
print('World') # aligned with block
returnAll statements inside the function body must be at the same indentation level — aligning the print call fixes the IndentationError.
How to diagnose
Enable visible whitespace in your editor to see tabs vs spaces and inconsistent indentation levels
Run python -m py_compile yourfile.py to get the exact line number of the indentation error
Use python -tt to treat tab/space inconsistency as an error and catch mixed indentation early
How to fix
Convert all tabs to spaces with a consistent width (PEP 8 recommends 4 spaces) using your editor
Align the indentation of the problematic line with the surrounding block's expected level
Remove accidental leading spaces on lines that should be at the top level of the module
How to prevent
Configure your editor to use spaces (not tabs) with a width of 4 and show whitespace characters
Use a linter like flake8 or ruff that detects indentation issues before running the code
Related Resources
Related Glossary
Related Lessons
- Python Syntax
Learn Python syntax rules.