Fix IndentationError in Python: 6 Causes and Exact Fixes (2026)
Python IndentationError means your whitespace is inconsistent or missing. Here are the 6 most common causes with exact code fixes including mixed tabs/spaces, empty blocks, and VS Code settings that prevent it permanently.
The Error
or
or
Python uses indentation as syntax. Unlike other languages where indentation is style, Python requires it to be correct and consistent. Every
IndentationError means the interpreter found whitespace it could not parse.
## The 6 Most Common Causes
### 1. Empty function or class body
Python expects at least one statement inside every def, class, if, for, while, or with block. An empty block is a syntax error.
Fix: add pass as a placeholder.
### 2. Mixed tabs and spaces
Your editor shows this looking fine. Python 3 does not allow mixing tabs and spaces in the same file. It throws TabError.
Fix: convert all indentation to spaces.
In VS Code: open Command Palette → Convert Indentation to Spaces. Set tab size to 4.
Add to your project's .editorconfig:
This enforces spaces for all Python files, regardless of editor.
### 3. Wrong level of dedent
The return is indented at a level that does not match any containing block. Python cannot figure out where it belongs.
Fix: align the dedent to a real block level.
### 4. Copy-pasted code with wrong indentation
Pasting from documentation, Stack Overflow, or a chat tool often introduces wrong indentation or invisible characters. The code looks correct
visually but Python disagrees.
Fix: select all pasted code → Tab → Shift+Tab to normalize indentation. Or use Reindent Lines in VS Code Command Palette.
### 5. Continuation line not indented
Inside parentheses, brackets, or braces, Python allows implicit line continuation — but continuation lines must still be indented relative to the
opening.
Fix:
### 6. Comment after colon with no real body
A comment does not count as the indented block. Python still expects a real statement.
Fix:
## How to Find It Fast
Python's IndentationError includes the file and line number. Go directly there.
VS Code tip: enable editor.renderWhitespace: "all" in settings to make spaces and tabs visible. Tabs show as →, spaces show as ·.
Instantly reveals mixed indentation.
Ruff: run ruff check . to catch IndentationErrors and whitespace issues before you run your code.
## Prevent It Permanently
.editorconfig (project root):
VS Code settings.json:
detectIndentation: false stops VS Code from guessing indent style from file content — which causes the mixed-indent problem when pasting code.
For errors that are harder to trace across files, DebugAI reads your terminal error and queries the relevant files directly
to find the exact line and root cause.
Debug faster starting today.
Free VS Code extension. 10 sessions/day. No credit card.