How to Resolve Error "IndentationError: expected an indented block" in Python
In Python, whitespace is not just cosmetic; it is syntactically significant. Python uses indentation to define the scope of loops, functions, classes, and conditional statements. The IndentationError: expected an indented block occurs when the Python interpreter encounters a line ending in a colon (:), indicating the start of a new block, but the subsequent line is not indented.
This guide explains the rules of Python indentation, how to identify problematic blocks, and how to resolve this common syntax error.
Understanding Python Indentation Rules
Unlike languages like C++ or Java that use curly braces {} to define code blocks, Python uses whitespace.
- Compound Statements: Statements like
if,for,while,def, andclassend with a colon (:). - The Rule: The line immediately following a colon must be indented relative to the line containing the colon.
- The Standard: PEP 8 (Python's style guide) recommends 4 spaces per indentation level.
Scenario 1: Missing Indentation After a Statement
This is the most direct cause of the error. You define a function or a loop header but fail to indent the body code.
Example of error
def greet_user():
print("Hello, User!") # ⛔️ Error: This line should be indented
Output:
File "script.py", line 2
print("Hello, User!")
^
IndentationError: expected an indented block after function definition on line 1
Solution
Indent the body of the function.
def greet_user():
# ✅ Correct: Standard 4-space indentation
print("Hello, User!")
greet_user()
Output:
Hello, User!
Scenario 2: Empty Blocks and the pass Keyword
Sometimes you declare a function or a conditional block but intend to write the logic later. Leaving it completely empty causes an IndentationError because Python expects something to be there.
Example of error
x = 10
if x > 5:
# ⛔️ Error: Comments do not count as an indented block.
# TODO: write logic here
print("Done")
Output:
File "script.py", line 6
print("Done")
^
IndentationError: expected an indented block after 'if' statement on line 3
Solution: Using pass
The pass keyword is a null operation in Python. It does nothing when executed, but it satisfies the requirement for an indented block.
x = 10
if x > 5:
# ✅ Correct: 'pass' acts as a placeholder
pass
print("Done")
Output:
Done
Use pass when creating skeleton code, abstract classes, or when a syntactical block is required but no action is needed.
Scenario 3: Inconsistent Indentation Levels
While the standard is 4 spaces, Python technically allows any amount of whitespace as long as it is consistent within the block. However, if you un-indent too much or too little within a nested structure, errors occur.
Example of Error
def calculate(a, b):
result = a + b
return result # ⛔️ Error: Indented with 3 spaces instead of 4
Output:
IndentationError: unindent does not match any outer indentation level
Solution
Ensure all lines in the same block align perfectly vertically.
def calculate(a, b):
result = a + b
# ✅ Correct: Aligns with the line above
return result
print(f"Sum: {calculate(5, 5)}")
Output:
Sum: 10
Best Practices and Tools
To avoid indentation headaches, follow these guidelines:
- Stick to 4 Spaces: Do not use 2 spaces or 8 spaces unless mandated by a specific legacy project.
- Tabs vs. Spaces: Never mix them. Python 3 disallows mixing tabs and spaces for indentation. Configure your text editor to "Insert Spaces" when you press the Tab key.
- Use a Linter: Tools like
flake8orpylintwill catch these errors before you even run the code. - Visual Studio Code / PyCharm: Most modern IDEs automatically handle indentation for you. If you paste code from the internet, right-click and select "Format Document" to fix alignment issues.
Code copied from PDF files or certain websites often contains invisible characters or mixed tabs/spaces that look correct visually but fail syntactically. If you get an IndentationError on a line that looks fine, try deleting the whitespace and typing the spaces again.
Conclusion
The IndentationError: expected an indented block is Python's way of enforcing structure. It occurs whenever a line ending in : is not followed by indented code.
- Check Colons: If a line ends in
:, the next line must be indented. - Use
pass: If a block is meant to be empty, insertpass. - Check Alignment: Ensure all lines in a block start at the exact same column.