What is "IndentationError: expected an indented block" in Python?

It is a common programming practice to indent code. Indentation uses spaces or tabs to separate the code for better visualization. This is important for code readability.

In Python, indentation is part of the syntax.

def foo()
    print("foo") // 1st level indentation
    if True:
        print("True") // 2nd level indentation.

print("Source") // No Indentation, part of source.

The code snippet above describes how to indent code in Python. Failing to adhere to these principles can lead to the “IndentationError: expected an indented block” error.

widget

When we say indentation, it is basically any consistent white space. However, it is common to use 4 spaces for indentation or apply tabulation to the code.

To resolve this error, check the following things:

  1. Check to see if you have left alone an else: part of an if-condition, and check if the indentation is missing after conditions, loops, etc.
x = 5
if x == 2:
print("x is 2") #indented
else:
print("x is not 2") #unindented
x = 5
if x == 2:
print("x is 2") #indented
else:
print("x is not 2") #indented
  1. Check the indentation of statements inside the function.
def print_msg(the_msg):
"""this doctring not indented"""

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved