Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Indentation Error in Python
3.
Python Indentation Ruling
4.
Causes of Indentation Error
5.
Unindented Statements
5.1.
Example
6.
An Empty Suite
6.1.
Example
7.
Documentation String
7.1.
Example
8.
Frequently Asked Questions
8.1.
What is an indentation in Python?
8.2.
How many whitespaces are present in Python for indentation?
8.3.
What is a docstring in Python?
8.4.
What are the comments in Python?
8.5.
Do we need to have an indentation for C++ and Java?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

IndentationError: expected an indented block in Python

Author Sohail Ali
1 upvote

Introduction

Hii Ninjas, so today we will solve the mystery of the most common error among programmers. This error bugs almost every programmer who has started his/her coding journey with Python. This error is called an indentation error in Python.

IndentationError: expected an indented block in Python

In this blog, we will look at what exactly causes this error and how to solve these errors in Python. So buckle up your belts, and let’s get started.

Indentation Error in Python

Almost every programming language out there offers an inbuild indentation facility. Programming languages like C++ and Java use curly braces to structure the code, while Python relies solely on indentation. An indentation simply means a space at the beginning of the line. 
If you are careless while writing the code and misplaced whitespaces or tabs in your code. In such cases, you will encounter an Indentation error in Python. The below diagram shows a general depiction of indentation.

Indentation error block diagram

In the above diagram, we can see that all the blocks are indented and nested properly. This is because the amount of whitespaces of each block from the left corner is exactly the same as the block end. Python follows the same type of indentation in its writing structure.

Python Indentation Ruling

Some general rules which need to be followed while writing code in Python are as follows:

  • No indentation at the start of the code.
     
  • The number of white spaces from the left corner of a code block should be consistent.
     
  • In Python, indentation is mandatory for each block of a statement.
     
  • By default, there are four whitespace indentations in Python. But there should be a minimum of one white space after each code block. The amount of indentation is decided solely by the user.

Causes of Indentation Error

We must give some indentation in Python after detecting an ‘:’ character in our code. For example, in the case of conditional statements, loops, and try-except statements, we encounter this character and are expected to give proper indentation. 
Let us now look at different scenarios where we can get this error.

Unindented Statements

You will get an indentation error whenever you miss giving an indentation at an expected place. This error can be avoided by providing proper space after each block of statements.

Example

# Function to check the condition
def CheckNumber(a):   

# Checking for a positive number  
if (a > 0):   
    print("Given number is positive")   

# Checking for a negative number   
elif (a < 0):   
    print("Given number is negative")  

# Else the number must be zero
else:   
    print("Given number is zero")  

num = -26
print("The number to check is:",num)
print()

# Printing the result 
CheckNumber(num) 
You can also try this code with Online Python Compiler
Run Code


Output

Unindented statement output error

Explanation

In the above example, we skipped to indent the code after we encountered a ‘:’ character at the end of the function. Thus we will get an error message ‘expected an indented block’.

Solution

Now, let’s fix the indentation issue and check the working of our Python code. After properly adding whitespaces, the code will look like the below:

# Function to check the condition
def CheckNumber(a):   
    # Checking for a positive number  
    if (a > 0):   
        print("Given number is positive")   

    # Checking for a negative number   
    elif (a < 0):   
        print("Given number is negative") 

    # Else the number must be zero
    else:   
        print("Given number is zero")  

num = -26
print("The number to check is:",num)
print()

# Printing the result 
CheckNumber(num) 
You can also try this code with Online Python Compiler
Run Code


Output

Unindented statement output

Explanation

In the above Python program, if you observe closely after adding indentation before each conditional statement, the error has been resolved, and we got our expected result.

Also see,  Convert String to List Python

An Empty Suite

Whenever we write a conditional statement, Python expects us not to leave it empty. If it is left empty then we will get an indentation error. Let us understand this case using an example.

Example

num = 10
# Checking for non-zero number
if(num != 0):
    # Do Something later
else:
    print("Number is Zero")

print("Outside if statement")
You can also try this code with Online Python Compiler
Run Code


Output

Empty suite output error

Explanation

In the above example, the if statement is left vacant, which results in the error ‘expected an indented block’. This happens because Python is looking for a statement whenever the if condition becomes true. But in our case, there is no statement after the if condition till the else condition. Therefore Python will throw an indentation error at the else condition.
 

Solution

Suppose you want to add some functionality later whenever the if condition gets satisfied. In order to fulfil this condition and at the same time avoid the error, we can use a pass keyword in Python. Let us look at the same example with the pass keyword this time.

num = 10
# Checking for non-zero number
if(num != 0):
    # Do Something later
    pass
else:
    print("Number is Zero")

print("Outside if statement")
You can also try this code with Online Python Compiler
Run Code


Output

Empty suite output

Explanation

In the above example, the pass keyword is used to skip the code block whenever the if condition gets satisfied. 

Documentation String

In Python, a documentation (Docstring) string is used to document the source code well. The programmer uses it to relook the function of a program and review the code. You can write a docstring using triple single quotes (’’’) or triple double quotes (“ “ “).

Example

def multiply(a, b):
""" Takes two numbers input and returns their product."""
    return a*b

# Initializing the numbers
a = 20
b = 53

# Calling the function
result = multiply(a,b)

# Printing the result
print("The multiplication is:", result)
You can also try this code with Online Python Compiler
Run Code


Output

Documentation String error output

Explanation

In the above example, we can see that the docstring is not intended properly in the multiply function. This will result in an indentation error indicating improper spacing. 

Solution

Let us indent the above code properly and check the output.

def multiply(a, b):
    """ Takes two numbers input and returns their product."""
    return a*b

# Initializing the numbers
a = 20
b = 53

# Calling the function
result = multiply(a,b)

# Printing the result
print("The multiplication is:", result)
You can also try this code with Online Python Compiler
Run Code

 

Output

Documentation String solution output

Explanation

In the above example, after intending the docstring, the error was resolved, and we got our expected result. 

Note: A regular Python comment (#) can avoid this error even if it is not correctly indented.

Frequently Asked Questions

What is an indentation in Python?

In Python, leading whitespace before a statement is called an indentation.

How many whitespaces are present in Python for indentation?

By default, Python has four whitespaces before each block statement for indentation. Users can give any number of consistent indentations of their choice. At least a single whitespace is a must in your code.

What is a docstring in Python?

A docstring (Documentation string) is a string literal that is written right after the definition of a function, class, or method. 

What are the comments in Python?

In Python, a comment is a line of code that the interpreter does not execute during the execution of the program.

Do we need to have an indentation for C++ and Java?

No, an indentation is not needed in the case of programming languages like C++ and Java.

Conclusion

This article discusses the indentation error that is ‘expected as an indented block in Python’. We also discussed various causes that may result in indentation errors in Python. We hope this blog has helped you enhance your knowledge of indentation errors in Python. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your coding ability, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass