Cookie Policy

We use cookies to operate this website, improve usability, personalize your experience, and improve our marketing. Privacy Policy.

By clicking "Accept" or further use of this website, you agree to allow cookies.

Accept
Learn Machine Learning by Doing Learn Now
You are reading solutions / Python
alfie-grace-headshot-square2.jpg
Author: Alfie Grace
Data Scientist

IndentationError: expected an indented block

LearnDataSci is reader-supported. When you purchase through links on our site, earned commissions help support our team of writers, researchers, and designers at no extra cost to you.

IndentationError: expected an indented block

Why Does This Occur?

As the error implies, this occurs after statements that require indenting, such as after if statements, for loops and try except exception handling.

Unlike many programming languages that use braces, Python requires indents to determine which code block belongs to a statement. More simply, after detecting the : character in your script, Python will look for an indent.

This lesson will quickly examine a few reasons when this error can occur and how to fix it.

Cause 1: Unindented Statement

Imagine you are looking at sales figures for Company A, which sells software packages. You want to write a script for determining which employees are meeting a certain sales threshold.

Using enumerate, we can iterate through employees and use the index as an ID for each employee. We can then print off a message showing if that employee hit the sales target or not.

The script below shows how we can execute this process:

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
print(f'Employee {employee_id + 1}:')

if employee_sales > 50:
    print('Hit sales target!\n')
else:
    print('Room for improvement.\n')
Out:
File "<ipython-input-7-8f5233f8cf0e>", line 4
    print(f'Employee {employee_id + 1}:')
    ^
IndentationError: expected an indented block

Although we've made the if else loop correctly, the for statement is causing an indentation error. This error is happening because we've provided a list for Python to iterate through in our for loop, but it doesn't know which logic it needs to apply while looping.

The straightforward fix is to add an indent at the line indicated in the error:

Solution

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')

if employee_sales > 50:
    print('Hit sales target!\n')
else:
    print('Room for improvement.\n')
Out:
Employee 1:
Employee 2:
Employee 3:
Hit sales target!

Now that Python has the correct structure, it will check the sales figure for each employee individually and consider if the number is greater than 50 or not. It will then print the corresponding message and move on to the next employee.

Cause 2: Empty Suite

When working on larger scripts, you'll often anticipate many if elif branches ahead of time by creating a branch and commenting on some logic you plan on filling in later.

Here's an example using our sales analysis script that we used previously:

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    if employee_sales > 50:
        # add functionality here to display that the employee hit their target
    else:
        print('Room for improvement.')
Out:
File "<ipython-input-9-d1e1fb64bfe8>", line 7
    else:
    ^
IndentationError: expected an indented block

In this case, Python throws the error because it's looking for a code block after the if statement, i.e., what your program should do if the statement is true. The code seems to be structured correctly, but the program will fail to run until the actual code is placed after the if.

Having a statement like this without anything following it is known as an empty suite. A quick fix for this is to use the pass keyword:

Solution

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    if employee_sales > 50:
        # add functionality here to display that the employee hit their target
        pass
    else:
        print('Room for improvement.')
Out:
Employee 1:
Employee 2:
Room for improvement.
Employee 3:

In this situation, the pass keyword allows Python to skip when the if is true. This command bypasses the indentation error, allowing us to work on other areas until we are ready to come back and write the functionality that displays a message.

Cause 3: Unindented Docstring

To keep code well-documented, we can use docstrings at the start of a function, class, or method to quickly say what the code does. This description is to make life easier for yourself and others when reviewing the code later.

To write a docstring, you use two sets of triple apostrophes (''') or quotes ("""), which makes multi-line comments in Python possible.

The example below shows how we can use a docstring to describe a function to contain the if-else loop we've been using in our sales analysis script.

def analyze_sales(sales_figure):
'''function used for taking sales figures as an input and outputting a message related to the target'''
    if sales_figure > 50:
        message = 'Hit sales target!\n'
    else:
        message = 'Room for improvement.\n'
    return message


company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    print(analyze_sales(employee_sales))
Out:
File "<ipython-input-13-e17405f37406>", line 2
    '''function used for taking sales figures as an input and outputting a message related to the target'''
    ^
IndentationError: expected an indented block

This script crashed because Python is looking for indentation at the start of the function. To fix this, we can add an indent to the docstring. Shown below is this solution in action:

Solution

def analyze_sales(sales_figure):
    '''function used for taking sales figures as an input and outputting a message related to the target'''
    if sales_figure > 50:
        message = 'Hit sales target!\n'
    else:
        message = 'Room for improvement.\n'
    return message


company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    print(analyze_sales(employee_sales))
Out:
Employee 1:
Hit sales target!

Employee 2:
Room for improvement.

Employee 3:
Hit sales target!

Note that in this example, using a regular comment (#) to mark the docstring would prevent the indentation error without the need to add an indent. Avoid doing this, though, as it's best practice to keep docstrings within two sets of triple apostrophes/quotes.

Summary

This error occurs when Python is looking for an indented block of code after certain types of statements. The indented block tells Python that the code within the block is relevant to the statement. This s}tructure is fundamental to the Python programming language, so it's no surprise incorrectly indenting things can make scripts malfunction! Luckily, this is an easy fix, and in most cases, all you need to do is quickly add an indent in the correct place, and you'll be good to go.


Meet the Authors

alfie-grace-headshot-square2.jpg

Alfie graduated with a Master's degree in Mechanical Engineering from University College London. He's currently working as Data Scientist at Square Enix. Find him on LinkedIn.

Brendan Martin
Editor: Brendan
Founder of LearnDataSci

Get updates in your inbox

Join over 7,500 data science learners.