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 indentedOutput:
File "script.py", line 2
print("Hello, User!")
^
IndentationError: expected an indented block after function definition on line 1Solution
Indent the body of the function.
def greet_user():
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:
print("Done")Output:
File "script.py", line 6
print("Done")
^
IndentationError: expected an indented block after 'if' statement on line 3Solution: 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:
pass
print("Done")Output:
DoneScenario 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 4Output:
IndentationError: unindent does not match any outer indentation levelSolution
Ensure all lines in the same block align perfectly vertically.
def calculate(a, b):
result = a + b
return result
print(f"Sum: {calculate(5, 5)}")Output:
Sum: 10Best 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.
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.