PyGuide

Learn Python with practical tutorials and code examples

How to Fix Python Indentation Errors

Understanding Python Indentation #

Python uses indentation to define code blocks, unlike other languages that use braces {} or keywords. This makes Python code readable but can cause errors if not done correctly.

Common Indentation Errors #

1. IndentationError: expected an indented block #

Problem:

if True:
print("Hello")  # Error: expected indentation

Solution:

if True:
    print("Hello")  # Correct: indented with 4 spaces

2. IndentationError: unindent does not match any outer indentation level #

Problem:

if True:
    print("First line")
  print("Second line")  # Error: inconsistent indentation

Solution:

if True:
    print("First line")
    print("Second line")  # Correct: consistent 4-space indentation

3. TabError: inconsistent use of tabs and spaces #

Problem:

if True:
    print("Using spaces")
    print("Using tab")  # Error: mixing tabs and spaces

Solution:

if True:
    print("Using spaces")
    print("Also using spaces")  # Correct: consistent spaces

Best Practices #

1. Use 4 Spaces (PEP 8 Standard) #

# Recommended
if condition:
    do_something()
    if nested_condition:
        do_nested_thing()

2. Configure Your Editor #

Most editors can show whitespace and auto-convert tabs:

VS Code:

  • Enable "Render Whitespace"
  • Set "Tab Size" to 4
  • Enable "Insert Spaces" instead of tabs

PyCharm:

  • Settings → Editor → Code Style → Python
  • Set tab size and indent to 4
  • Use spaces for indentation

3. Use Consistent Indentation Throughout Your Project #

class MyClass:
    def __init__(self):
        self.value = 0
    
    def method(self):
        if self.value > 0:
            return True
        else:
            return False

Debugging Indentation Issues #

1. Make Whitespace Visible #

# Use your editor's "show whitespace" feature
# Or check in terminal:
cat -A your_file.py  # Shows tabs as ^I and spaces as dots

2. Check Line by Line #

# Python will tell you the exact line number:
# File "example.py", line 5
#     print("Hello")
#     ^
# IndentationError: expected an indented block

3. Use Python's Built-in Tools #

# Check your code with Python's syntax checker
python -m py_compile your_file.py

# Use flake8 for style checking
pip install flake8
flake8 your_file.py

Common Scenarios and Solutions #

Functions and Classes #

# Correct function indentation
def greet(name):
    message = f"Hello, {name}!"
    return message

# Correct class indentation
class Person:
    def __init__(self, name):
        self.name = name
    
    def introduce(self):
        return f"I'm {self.name}"

Loops and Conditionals #

# Correct loop indentation
for i in range(5):
    print(f"Number: {i}")
    if i % 2 == 0:
        print("Even")
    else:
        print("Odd")

# Correct nested conditions
if weather == "sunny":
    print("Great day!")
    if temperature > 25:
        print("Perfect for swimming")
        if have_sunscreen:
            print("Don't forget sunscreen!")

Try-Except Blocks #

# Correct exception handling indentation
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
    result = None
finally:
    print("Cleanup code here")

Fixing Mixed Tabs and Spaces #

Method 1: Find and Replace in Editor #

  1. Enable "Show Whitespace" in your editor
  2. Select all tabs and replace with 4 spaces
  3. Save the file

Method 2: Python Script #

# fix_indentation.py
import re

def fix_file_indentation(filename):
    with open(filename, 'r') as file:
        content = file.read()
    
    # Replace tabs with 4 spaces
    fixed_content = content.expandtabs(4)
    
    with open(filename, 'w') as file:
        file.write(fixed_content)
    
    print(f"Fixed indentation in {filename}")

# Usage
fix_file_indentation("your_script.py")

Method 3: Command Line Tools #

# Using autopep8
pip install autopep8
autopep8 --in-place --select=E101,E111,E112,E113 your_file.py

# Using black (reformats entire file)
pip install black
black your_file.py

Quick Reference #

Valid Indentation Patterns: #

# 4 spaces (recommended)
if True:
    print("Hello")

# 2 spaces (acceptable but not recommended)
if True:
  print("Hello")

# 8 spaces (acceptable for continuation lines)
result = some_very_long_function_name(
        argument1, argument2, argument3)

Invalid Patterns: #

# No indentation
if True:
print("Error")

# Mixed indentation
if True:
    print("Spaces")
    print("Tab - Error!")

# Inconsistent indentation
if True:
    print("4 spaces")
      print("6 spaces - Error!")

Prevention Tips #

  1. Configure your editor to show whitespace characters
  2. Set up auto-formatting with tools like Black or autopep8
  3. Use a linter like flake8 or pylint in your development workflow
  4. Be consistent within your project and team
  5. Use version control hooks to check formatting before commits

When You're Still Stuck #

If you're still getting indentation errors:

  1. Copy your code to a new file and re-type the indentation
  2. Use an online Python formatter to check your code
  3. Check for invisible characters that might be causing issues
  4. Compare with working code to see the difference
  5. Ask for help on Stack Overflow with your specific error message

Remember: Python's indentation might seem strict at first, but it leads to more readable and consistent code!