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
IndentationError
Example
An example of when this exception appears:
>>> 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:
>>> 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:
>>> def calculate_area(radius):
... area = 3.14 * radius ** 2
... return area
...
Related Resources
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.
For additional information on related topics, take a look at the following resources: