← Back to DevBytes

Fix 'IndentationError' in Python

Understanding IndentationError in Python

IndentationError is one of the most common stumbling blocks for newcomers to Python—and occasionally even for experienced developers switching between editors. Unlike languages such as Java or C++ that use braces {} to define code blocks, Python relies solely on indentation to group statements. When the indentation is inconsistent, missing, or misaligned, Python raises an IndentationError, refusing to run the code until the issue is resolved.

What Causes IndentationError?

Python’s parser expects all lines within the same block to share the same leading whitespace. An IndentationError typically surfaces in one of these forms:

Consider this classic mistake:

def greet():
print("Hello, world!")   # Missing indentation under the function header

Running the snippet produces:

IndentationError: expected an indented block after function definition

Even a single misplaced space can break a program that looks perfectly fine on screen.

Why Proper Indentation Matters

Indentation in Python is not cosmetic—it defines the logical structure of your code. A consistent indentation style directly impacts readability, maintainability, and the correctness of control flow. For example, a loop body or the branch of an if statement is determined entirely by indentation, so a wrong indent silently changes program behavior:

for i in range(3):
    print("Iteration", i)
print("Loop finished")   # This line is inside the loop if indented, outside if not

If the last line is accidentally indented to match the loop body, it becomes part of the loop and prints three times instead of once. Without braces, Python forces you to be precise, which ultimately reduces ambiguity and enhances code clarity when done correctly.

How to Fix IndentationError

Fixing indentation issues is straightforward once you know the common patterns. Follow this systematic approach:

1. Locate the exact line and error type

Python’s traceback points to the line where the parser got confused. Read the error message carefully—it tells you whether an indent was unexpected, missing, or if tabs and spaces were mixed.

File "script.py", line 5
    print("Unexpected indent")
    ^
IndentationError: unexpected indent

2. Reveal hidden whitespace

Most modern editors can show whitespace characters. Enable “show whitespace” or “show invisibles” in your editor settings. Tabs appear as arrows or long dashes; spaces appear as dots. This immediately exposes mixing.

3. Convert all indentation to spaces (or tabs, but spaces are recommended)

Python’s style guide (PEP 8) recommends 4 spaces per indentation level. Use your editor’s “Convert Indentation to Spaces” command to normalize the entire file. For example, in VS Code you can run Convert Indentation to Spaces from the command palette.

4. Reindent the block consistently

Highlight the affected lines and use the editor’s automatic indentation correction or manually align them to the same level. Ensure all lines inside a compound statement have exactly the same leading whitespace.

Example fix for the missing indent above:

def greet():
    print("Hello, world!")   # Now correctly indented with 4 spaces

If you accidentally mix tabs and spaces, the file might look like:

def process(data):
    result = []
    for item in data:       # This line uses tabs
        result.append(item * 2)   # This line uses spaces, mismatch

After revealing whitespace and converting all tabs to spaces:

def process(data):
    result = []
    for item in data:
        result.append(item * 2)   # Uniform 4-space indentation

5. Use editor tools to detect and fix automatically

Linters and formatters like pylint, flake8, or black will flag indentation problems and can reformat your code to a consistent style. Running black on a file normalizes indentation instantly.

Best Practices to Avoid IndentationError

Common Pitfalls and How to Correct Them

Empty blocks: A function or class with no body must include a docstring or pass statement to satisfy the indentation requirement.

# Wrong – empty block triggers IndentationError
def empty():
    
# Correct
def empty():
    pass

Indentation inside multi-line strings: Indentation in triple-quoted strings can confuse the parser if the string is not properly closed. Make sure the string content does not interfere with the surrounding block.

Mixing indentation in try/except chains: All except, finally, and else clauses must align with the try keyword.

try:
    risky_call()
except ValueError:    # Must match 'try' indentation
    handle_error()
finally:              # Same level
    cleanup()

Conditional blocks and loops inside other blocks: Keep track of indentation depth manually when nesting. A common mistake is to dedent one level too many after a nested loop, causing subsequent code to fall outside the intended outer block.

Conclusion

IndentationError is a protective mechanism that ensures Python code remains structured and readable. By understanding that indentation defines logic, using the same whitespace style everywhere, and leveraging modern editor tools to visualize and normalize indentation, you can eliminate this error from your development workflow. Embrace consistent indentation as a discipline—it not only prevents runtime failures but also makes your codebase cleaner, more maintainable, and easier to collaborate on. Once you adopt the practices above, you’ll rarely encounter an IndentationError again.

🚀 Need a reliable AI agent for your project?

Deploy Hermes Agent in 10 minutes. Managed hosting, zero DevOps.

Get Started — $23.99/mo
← Back to all articles