IndentationError

IndentationError is a built-in exception that Python raises when your code’s indentation is incorrect.

Because Python uses indentation to define code blocks, you must consistently use spaces or tabs so Python can parse your code correctly. If your indentation doesn’t match up, Python raises an IndentationError to let you know there’s a problem with how your code is structured.

To avoid these errors, you’ll need to ensure your code blocks are properly aligned. Most developers use four spaces for each indentation level.

IndentationError Occurs When

  • Mixing spaces and tabs for indentation
  • Accidentally adding or removing spaces at the beginning of a line
  • Copying and pasting code that introduces inconsistent indentation
  • Defining a new code block (like a function or loop) without proper indentation

IndentationError Example

An example of when this exception appears:

Python
>>> def greet(name):
...     print(f"Hello, {name}!")
...   print("Welcome to Real Python!")
  File "<stdin>", line 3
    print("Welcome to Real Python!")
                                   ^
IndentationError: unindent does not match any outer indentation level

You typically won’t raise an IndentationError manually in your code. Python’s parser automatically raises this exception when it detects improper indentation.

IndentationError How to Fix It

Consider the following code with inconsistent indentation:

Python
>>> def calculate_area(radius):
...     area = 3.14 * radius ** 2
...    return area
  File "<stdin>", line 3
    return area
              ^
IndentationError: unindent does not match any outer indentation level

To fix this function, make sure all lines within the function share the same indentation level:

Python
>>> def calculate_area(radius):
...     area = 3.14 * radius ** 2
...     return area
...

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 17, 2025 • Reviewed by Martin Breuss