Quick Answer
Python requires consistent indentation after colons in control structures. Use 4 spaces (recommended) or tabs consistently. Add pass statement for empty blocks.
Understanding the Issue
Python uses indentation to define code blocks instead of curly braces. IndentationError occurs when the expected indented block is missing or incorrectly formatted after control structures like if, for, while, function definitions, or class definitions. Consistent indentation is crucial for Python syntax.
The Problem
This code demonstrates the issue:
Python
Error
# Problem 1: Missing indentation after control structure
if True:
print("This should be indented") # IndentationError: expected an indented block
# Problem 2: Empty function or class without pass statement
def my_function():
# IndentationError: expected an indented block (nothing after colon)
The Solution
Here's the corrected code:
Python
Fixed
# Solution 1: Proper indentation after control structures
# Correct if statement with indentation
if True:
print("This is properly indented") # 4 spaces indentation
print("This continues the block")
# Correct function definition
def my_function():
print("Function body is indented")
return "Success"
# Correct loop structure
for i in range(3):
print(f"Iteration {i}")
if i == 1:
print(" This is nested indentation")
# Solution 2: Handling empty blocks and complex structures
# Use pass for empty blocks
def placeholder_function():
pass # Placeholder for future implementation
class EmptyClass:
pass # Empty class definition
# Complex nested structure with consistent indentation
def process_data(data):
if data:
for item in data:
if item > 0:
print(f"Processing positive item: {item}")
result = item * 2
if result > 10:
print(f"Large result: {result}")
else:
print(f"Small result: {result}")
else:
print(f"Skipping non-positive item: {item}")
else:
print("No data to process")
# Example usage
sample_data = [1, -2, 5, 0, 8]
process_data(sample_data)
# Proper exception handling indentation
try:
risky_operation = 10 / 2
print(f"Result: {risky_operation}")
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Cleanup completed")
Key Takeaways
Always indent code blocks after colons using 4 spaces consistently. Use pass statement for empty functions, classes, or control blocks. Maintain consistent indentation levels for nested structures.