Solving the “IndentationError: expected an indented block” error

by Alex
Solving the "IndentationError: expected an indented block" error

Indentation in Python is strict. It’s very important to respect them in your code. If indentations, spaces, or tabs are not arranged correctly in your program, you will get an IndentationError: expected an intended block. In this tutorial we will look at what this error is and when it occurs. Let’s look at an example and see how to solve this problem.

IndentationError: expected an indented block

Programming languages like C and JavaScript do not require indentation. They use braces to structure code. Python does not have these braces. The structure of the program is created with indentation. Without them, the interpreter will not be able to recognize different blocks of code correctly. Let’s take this code as an example:

def find_average(grades):
average = sum(grades) / len(grades)
return average

How does Python know which code is part of find_average() and which is part of the main program? This is why indentation is so important. Every time you forget to put spaces or tabs, Python reminds you with an indentation error.

Example of an indentation error

Let’s write a program that extracts all the bagels from the food list on the menu. They will then be added to a separate list. First, let’s create a list of all the food:

lunch_menu = ["Bagel with Cheese", "Sandwich with Cheese", "Sandwich with Cucumber", "Bagel with Salmon"]

The menu contains two sandwiches and two bagels. Now write a function that creates a new bagel list based on the contents of the lunch_menu list:

def get_bagels(menu):
bagels = []
for m in menu:
if "bagel" in m:
return bagels

get_bagels() takes one argument, the menu list, which it traverses in search of the desired items. It checks if the item contains the word “Bagel” and, if so, will add it to the new list. Finally, the function needs to be called and output the result:

bagels = get_bagels(lunch_menu)

This code calls get_bagels() and outputs a list of bagels to the console. Let’s run the code and see the result:

File "", line 4
bagels = []
IndentationError: expected an indented block


Addressing the IndentationError

The indentation error reports that the indentation has not been set correctly. It needs to be added on line 4. Let’s take a look at the code:

def get_bagels(menu):
bagels = []

The value of the bagels variable should be assigned inside the function, but it is not, which leads to the error. To solve the problem we need to add an indentation:

def get_bagels(menu):
bagels = []

Now let’s run the code:

['Bagel with cheese', 'Bagel with salmon']

The code found all the bagels and added them to the new list. After that it outputs it to the console.

The output is

The error IndentationError: expected an indented block occurs if you forget to add an indentation in your code. To fix it, you need to check all indentations that should be present.

Related Posts