Online Tutorials & Training Materials | STechies.com
Register Login

IndentationError: expected an indented block

27 Jan 2020 2:45 pm || 0

Most programming languages such as Java and C offer the facility to indent the code. This is done through the use of brackets and curly braces. But in Python, the rules of indentation are very strict. This is because whitespaces and tabs are used to indent code. If you are not careful while indenting a piece of code, you will encounter an error called “IndentationError expected an indented block”. This error is raised when code within a statement such as main() function is not indented properly.

The way to solve this error is by checking whether the code is indented consistently all throughout the code. In this article, we will look at this error and understand the ways to fix it.

IndentationError expected an indented block

 

IndentationError: expected an indented block

Error:

a = int(input("Please enter an integer A: "))
b = int(input("Please enter an integer B: "))
if b > a:
print("B is greater than A")
elif a == b:
   print("A and B are equal")
else:
   print("A is greater than B")

Output:

File "t.py", line 4
    print("B is greater than A")
        ^
IndentationError: expected an indented block

In the above example, as you can see, we have assigned different indent to condition at line 4 and condition at line 6 within the same statement. That’s why it throws the error.

IndentationError: expected an indented block

Solution:

a = int(input("Please enter an integer A: "))
b = int(input("Please enter an integer B: "))
if b > a:
    print("B is greater than A")
elif a == b:
    print("A and B are equal")
else:
    print("A is greater than B")

Now the code will run successfully as all tabs are properly placed.

Python checks the indentation levels to determine where code blocks start and end. Proper indentation allows all code blocks to be read properly by Python.