IndentationError
IndentationError: unexpected indent
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
print("hello")
IndentationError: unexpected indentWhat causes this error
The indentation level of a line does not match any expected block structure. This often happens when tabs and spaces are mixed, when a line is indented where it should not be, or when the body of a compound statement is not indented at all.
How to fix it
Configure your editor to insert spaces instead of tabs and use a consistent indent width (4 spaces is standard). Use the editor's 'show whitespace' feature to spot invisible tab/space mixing.
Code that causes this error
def greet():
print("hello")Fixed code
def greet():
print("hello")About IndentationError
An IndentationError occurs when Python finds that the whitespace at the beginning of a line does not match any expected indentation level. Python uses indentation to delimit code blocks rather than braces, so consistent whitespace is syntactically significant. This error is a subclass of SyntaxError and is raised during the parsing phase before execution begins.
The most frequent causes are mixing tabs and spaces, forgetting to indent the body of a function, class, loop, or conditional, and adding extra spaces to a line that should be at a lower indentation level. Modern editors can be configured to convert tabs to spaces automatically, which eliminates the most stubborn variant of this error. When collaborating on code, agreeing on a consistent indentation style — typically four spaces — prevents these issues from appearing in version control diffs.
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