You run your script and Python won't even start it:
IndentationError: expected an indented block after 'if' statement on line 2
This error shows up before any of your code runs. Python reads the whole file first, and indentation is part of the grammar. Below are the six indentation errors you'll hit most often. You'll see the exact message for each one, how to fix it, and how to keep your editor from causing them. I ran every example on Python 3.11, 3.12 and 3.14. The messages match on all three. Only the spot where the ^ marker sits changes.
Why Python Cares About Indentation
Plenty of languages group statements with braces { }. Python uses indentation instead. The lines pushed to the right under an if, for, def or class are the body of that statement. So a line shifted by the wrong amount isn't just messy. It changes the structure, and Python reports an error.
Use four spaces per level and no tabs. The rest of this post shows what breaks when you don't.
The Six Errors
1. IndentationError: expected an indented block
age = 20
if age >= 18:
print("adult")
Any line that ends with a colon (if, elif, else, for, while, def, class, try, except, with) needs at least one indented line under it. From Python 3.10 on, the message names the statement: expected an indented block after 'if' statement on line 2. Older versions just say expected an indented block. Indent the body:
age = 20
if age >= 18:
print("adult")
2. IndentationError: unexpected indent
name = "Sam"
print("Hello,", name)
The second line is indented, but nothing above it opened a block. It has nothing to belong to. You'll often see this after pasting code. It also happens when you delete a line like if x: and forget to un-indent what sat under it. Take the extra indentation out:
name = "Sam"
print("Hello,", name)
3. IndentationError: unindent does not match any outer indentation level
def greet(name):
message = "Hello, " + name
return message
print(greet("Sam"))
The first line of the function body has eight spaces. The return has four. Nobody ever opened a four-space level, so Python can't tell which block that line is in. Give every line in the same block the same indentation:
def greet(name):
message = "Hello, " + name
return message
print(greet("Sam"))
4. TabError: inconsistent use of tabs and spaces
You can't see this one in most editors. In the example below, s += p is indented with eight spaces, and return s uses a single tab. They can look lined up on screen. Python won't guess how wide a tab is:
def total(prices):
s = 0
for p in prices:
s += p
return s
print(total([1, 2, 3]))
The error reads TabError: inconsistent use of tabs and spaces in indentation. Python 3 won't let you mix them in one block. So use spaces only. Most editors can show hidden characters and turn tabs into spaces for you. In VS Code, open the command palette and run Convert Indentation to Spaces:
def total(prices):
s = 0
for p in prices:
s += p
return s
print(total([1, 2, 3]))
5. A Function or Class With Only a Comment
def load_settings():
# TODO: read the settings file
def main():
load_settings()
print("started")
main()
A comment isn't a statement. To Python, load_settings has no body. The error lands on the next line, def main():, and says expected an indented block after function definition on line 1. That trips people up, because the real mistake is above it. Need an empty placeholder? Write pass (or ...):
def load_settings():
# TODO: read the settings file
pass
def main():
load_settings()
print("started")
main()
6. try / except / else Not Lined Up
try:
value = int("12")
except ValueError:
print("not a number")
else:
print(value)
The print under except ValueError: has no indentation, so the except block is empty. Python 3.10 and later says expected an indented block after 'except' statement on line 3. You'll get the same kind of error for else, finally, elif, with and class. Keep try, except, else and finally lined up with each other. Then move everything under each one in a level:
try:
value = int("12")
except ValueError:
print("not a number")
else:
print(value)
A Seventh Problem: No Error at All
Some indentation mistakes raise nothing. Say a line sits at a valid but wrong level. The program runs and quietly does the wrong thing. A return inside a for loop instead of after it stops the loop after one item. A print inside a loop, when you meant it to run once, prints over and over. Python can't warn you, because both versions are valid programs. If a result looks wrong and nothing crashes, look at the indentation around the loop or if.
How to Stop Fighting Indentation
Configure the editor once. Make Tab insert four spaces, and turn on "show whitespace". In VS Code the settings are editor.insertSpaces and editor.renderWhitespace. IDLE, PyCharm and most editors already do this for .py files.
Fix pasted code in one step. After you paste, select the block and use your editor's re-indent command. Or run a formatter such as black, which rewrites the indentation to be consistent. You can also check a file without running it. Use python -m py_compile yourfile.py, which reports the same errors.
Never mix tabs and spaces in a file, even when the lines look aligned. Python 3 rejects it. Old scripts you download are the usual source, since Python 2 code sometimes depended on tabs being eight spaces.
Quick Reference
| Message | Cause | Fix |
|---|---|---|
expected an indented block after ... |
A line ending in : has no indented body |
Indent the body, or write pass
|
unexpected indent |
A line is indented with no block above it | Remove the indentation |
unindent does not match any outer indentation level |
A line dedents to a level that was never opened | Use the same indentation for the whole block |
TabError: inconsistent use of tabs and spaces |
Tabs and spaces mixed in one block | Convert everything to spaces |
| Error points one line too low | A comment-only body above it | Add pass to the empty block |
The Rule, Stated Once
In Python, indentation is the structure of your code. Every line ending in a colon needs an indented body. Every line in a block uses the same indentation. A file uses spaces only. When Python raises an IndentationError, it points at the line where it noticed the problem. That's often one line after the real mistake, so check the line above too.
Want more Python errors with a clear cause? Try IndexError: List Index Out of Range, UnboundLocalError, ModuleNotFoundError After pip install and Tkinter TclError: Image Doesn’t Exist. If Python is new to you, start with Python for Beginners.
Download the code: the broken and fixed versions of all six errors are on GitHub in Python-projects/Troubleshooting/indentationerror. Run any file with python bug.py from inside its folder.
Top comments (0)