IndentationError
IndentationError: unexpected indent
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
y = 10 # unexpected indent
IndentationError: unexpected indentWhat causes this error
A line has more indentation than the block structure allows. Extra whitespace was added accidentally, or code was pasted with incorrect indentation.
How to fix it
Remove the extra indentation. Use your editor's indent guides to visualize block structure. Enable 'show whitespace' in your editor. Use an auto-formatter like black to fix indentation automatically.
Code that causes this error
x = 5
y = 10 # unexpected indentFixed code
x = 5 y = 10
About IndentationError
This error occurs when a line is indented more than expected by the current block structure. Python expects indentation to increase only after compound statements (if, for, while, def, class, with, try, etc.) and to return to the previous level after the block ends. An unexpected indent means a line has more leading whitespace than its context allows.
Common triggers include extra spaces or tabs added accidentally, copy-pasting code from different indentation contexts, and adding a line to a block without matching its indentation level. This error is caught during parsing, so no code executes before it is reported. Editors with indent guides (vertical lines showing indentation levels) make it much easier to keep indentation consistent.
Common scenarios
Writing code with missing colons, parentheses, or brackets
Mixing Python 2 and Python 3 syntax when upgrading a codebase
Copy-pasting code from the web with formatting issues or invisible characters
Using reserved keywords as variable or function names