How to Fix Python Indentation Error Unexpected Indent Beginner Guide
Python's indentation system is fundamental to the language, but it's also one of the most common sources of errors for beginners. If you're seeing "IndentationError: unexpected indent" or similar messages, this comprehensive guide will help you understand and fix these issues quickly.
Understanding Python Indentation #
Python uses indentation to define code blocks instead of curly braces like other languages. Every line of code at the same indentation level belongs to the same block.
🐍 Try it yourself
Common Indentation Error Types #
1. IndentationError: unexpected indent #
This occurs when Python encounters indentation where it doesn't expect it:
# Wrong - unexpected indent
print("Hello")
print("This line is incorrectly indented")
Fix: Remove the extra indentation:
🐍 Try it yourself
2. IndentationError: expected an indented block #
This happens when Python expects indentation but doesn't find it:
# Wrong - missing indentation
if True:
print("This should be indented")
Fix: Add proper indentation:
🐍 Try it yourself
Step-by-Step Debugging Process #
Step 1: Identify the Error Line #
When you see an indentation error, Python tells you exactly where the problem is:
IndentationError: unexpected indent
File "example.py", line 5
print("Problem here")
^
Step 2: Check Your Text Editor Settings #
Ensure your editor shows whitespace characters:
🐍 Try it yourself
Step 3: Choose Consistent Indentation #
Python recommends 4 spaces per indentation level:
🐍 Try it yourself
Common Mistake Scenarios #
Mixed Tabs and Spaces #
This is the most common cause of unexpected indent errors:
# Wrong - mixing tabs and spaces
def example():
print("Using spaces") # 4 spaces
print("Using tab") # 1 tab - ERROR!
Fix: Use only spaces or only tabs consistently:
🐍 Try it yourself
Incorrect Nesting Levels #
# Wrong - incorrect nesting
if True:
if True:
print("Wrong indentation level")
Fix: Match indentation levels properly:
🐍 Try it yourself
Fixing Tools and Techniques #
Using Python's Built-in Help #
🐍 Try it yourself
Text Editor Configuration #
Most editors can help prevent indentation errors:
- Enable "Show Whitespace" - See spaces and tabs visually
- Set "Tab Size" to 4 - Consistent with Python standards
- Enable "Insert Spaces for Tabs" - Avoid mixing
- Use "Auto-indent" - Automatic proper indentation
Real-World Example: Fixing a Complete Function #
Here's a common scenario with multiple indentation issues:
# Problem code with multiple indentation errors
def process_grades(students):
grades = [] # Missing indent
for student in students:
if student['score'] >= 90:
grade = 'A' # Missing indent
elif student['score'] >= 80: # Mixed tab/space
grade = 'B'
else:
grade = 'F'
grades.append(grade) # Wrong indent level
return grades # Missing indent
Fixed version:
🐍 Try it yourself
Prevention Best Practices #
1. Configure Your Editor Properly #
- Set tab size to 4 spaces
- Enable visible whitespace
- Use auto-indentation
- Set up Python linting
2. Use Consistent Style #
🐍 Try it yourself
3. Use Code Formatters #
Consider using tools like black or autopep8 to automatically format your code:
# Install with: pip install black
# Run with: black your_file.py
Common Mistakes to Avoid #
- Never mix tabs and spaces - Choose one and stick with it
- Don't assume indentation - Always check what your editor is inserting
- Watch for copy-paste issues - Code from different sources may have different indentation
- Be consistent with nesting levels - Each level should be exactly 4 spaces deeper
Quick Debugging Checklist #
When you encounter an indentation error:
- Check the exact line number in the error message
- Verify you're using consistent spacing (spaces or tabs, not both)
- Ensure each indentation level increases by exactly 4 spaces
- Look for missing colons (
:) after control statements - Check that all lines at the same logical level have identical indentation
Summary #
Python indentation errors are common but easily fixable once you understand the rules:
- Use 4 spaces per indentation level
- Never mix tabs and spaces
- Keep indentation consistent within the same block
- Configure your editor to help prevent issues
- Use Python's error messages to locate problems quickly
With practice and proper editor setup, indentation errors will become rare in your Python code. Remember that Python's indentation system, while initially challenging, makes your code more readable and maintainable once mastered.