Python Indentation Error Simply Explained

Posted by Marta on February 2, 2023 Viewed 2600 times

Card image cap

Hey there! This article will help understand the python indentation rules and when and why you could encounter a python indentation error.

Understanding how the indentation works in python is fundamental because code wrongly indent will not even compile.

In plain English, indentation means the state of being indented. And indented means leaving a space between a paragraph and the left or right margin. In python, it means the same. The indentation is the spaces at the beginning of a code line.

In python, indentation is used to define code blocks and therefore structure your code. Line codes that have the same indentation level are part of the same code block. Why is indentation significant? Indentation is a requirement in the python language, plus it is helpful since it makes the code easier to read and understand.

python indentation

Let’s see an example of some python indented code:

age = input('Please enter age: ')
age = int(age)
if(age > 18):
    # Code block
    print('You are older than 18')
else:
    # Code block
    print('You are not old enough')

Python Indentation Rules

There are rules defined in python referring to when you should start a new code block. Let’s go through the essential rules to remember:

If statements

Python expects that you create a code block inside every if statement. See the example below:

age = 6
if(age > 18):
    # Code block
    print('You are older than 18')
    print('Another line')
    #End block
print('End')

The following examples shows indentation errors:

age = 6
if(age > 18):
print('You are older than 18')   
print('End')

Output:

 File line 4
    print('You are older than 18')
        ^
IndentationError: expected an indented block

Another example of the wrong indentation. In this example, the problem is that all lines should have the same indentation level in a code block. In other words, the same spaces between the left margin and the code line.

age = 6
if(age > 18):
    print('You are older than 18')
      print('Another line')
print('End')

Output:

File line 4
    print('Another line')
    ^
IndentationError: unexpected indent

Loops

The python language also expect a code block inside the loop. This includes all loop types: for, while and do-while loop. Here is an example of correct indentation:

languages = ['Go','Javascript','Java','Python','Perl']
for language in languages:
    print(language)
    print('Another line')
print('End')

Wrong indentation examples:

Example #1

languages = ['Go','Javascript','Java','Python','Perl']
for language in languages:
print(language)
    
print('End')

Example #2

languages = ['Go','Javascript','Java','Python','Perl']
for language in languages:
    print(language)
      print('Another line')
print('End')

Functions

Python also expects a new code block indented within a function. The indentation helps python to determine the code that belongs to the function. Let’s see this in practice in an example of a correct indented function:

def print_languages():
    languages = ['Go','Javascript','Java','Python','Perl']
    for language in languages:
        print(language)

print_languages()

Wrong indentation examples:

Example #1

def print_languages():
languages = ['Go','Javascript','Java','Python','Perl']
for language in languages:
    print(language)

print_languages()

Output:

  File line 3
    languages = ['Go','Javascript','Java','Python','Perl']
            ^
IndentationError: expected an indented block

Classes

In python, when you define a class, python expects that all code that belongs to this class is indented. See an example below of a python function correctly indented:

class LanguageManager():
    def print_languages(self):
        languages = ['Go','Javascript','Java','Python','Perl']
        for language in languages:
            print(language)

LanguageManager().print_languages()

Ouput:

Go
Javascript
Java
Python
Perl

Python Indentation Error

In general, python expects a new code block indented after every semicolon, therefore after an if, loop, function, and class statement:

if(age > 18):
for language in languages:
def print_languages():
class LanguageManager():

Plus, all statements that belong to the code block should be aligned or the same indentation level. However, if there is a statement inside this block, ending with semicolon, you should indent any code inside the if as well. In other words, a nested code block. See this in action below:

class LanguageManager():
    def print_languages(self):
        languages = ['Go','Javascript','Java','Python','Perl']
        for language in languages:
            if(language.startswith('J')):
                print(language)

LanguageManager().print_languages()

As you can see, after every semicolon, there is a new code block.

Here are some examples that will result in python indentation compilation error:

Example #1

class LanguageManager():
    def print_languages(self):
        languages = ['Go','Javascript','Java','Python','Perl']
        for language in languages:
            if(language.startswith('J')):
            print(language)

LanguageManager().print_languages()

Output:

  File line 7
    print(language)
        ^
IndentationError: expected an indented block

Example #2

class LanguageManager():
    def print_languages(self):
        languages = ['Go','Javascript','Java','Python','Perl']
        for language in languages:
            if(language.startswith('J')):
                print(language)

    LanguageManager().print_languages()

Output:

File line 9, in LanguageManager
    LanguageManager().print_languages()
NameError: name 'LanguageManager' is not defined

Although in the code above, the error doesn’t mention anything about indentation, the error is caused by incorrectly indenting line 9. Since this line is using the LanguageManager class, this statement should be out of the class definition, in other words, not indented.

Conclusion

To summarise, you should indent the code the follows a semicolon, therefore after every if, loop, function statements or class you should indent the code underneath. Hope this article was helpful and you got a better understanding of how indentation works in python.

Thanks for reading and supporting the blog. Happy Coding!! 🙂

More Interesting Articles

How to Fix Typeerror a bytes-like object is required not ‘str’

Problem solving with algorithms and data structures review

Python assignments for Practice – Plan a delivery route

Types of Data Structures in Python

Python Unit Testing Frameworks with examples

How to Calculate the Running Time of an Algorithm – Big O Notation

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java