Indentation Error in Python (original) (raw)

Last Updated : 13 Sep, 2025

In Python, an Indentation Error occurs when the code is not properly aligned. Since Python relies on indentation to define code blocks, even a small misalignment can prevent the program from running.

In many languages like C, C++ or Java, code blocks are defined using braces { }. This means indentation is optional and mainly used just to improve readability.

Unlike C, C++ or Java, Python does not use braces at all. Indentation itself defines the block structure and determines which statements belong together. **For example:

Python `

if a > 2: if a < 7: return "Number is between 2 and 7"

`

Here, spaces before each line show Python which statements belong to the if block. That’s why proper alignment is not optional, but strictly mandatory in Python.

Cause of Indentation Error

Indentation errors usually happen because of small mistakes. Common causes include:

Here’s a program with incorrect indentation:

Python `

def check_number(a): if a > 2: if a < 7: return "Number is between 2 and 7" return "Number is greater than 2" return "Number is out of the range of 2 and 7"

a = 5 result = check_number(a) print(result)

`

**Output

IndentationError: expected an indented block

Why did this happen?

Fixing Indentation Errors

Proper indentation not only prevents errors but also improves readability. It makes your code easier for others (and yourself) to understand.

Now let’s fix the indentation properly:

Python `

def check_number(a): if a > 2: if a < 7: return "Number is between 2 and 7" return "Number is greater than 2" return "Number is out of the range of 2 and 7"

a = 5 result = check_number(a) print(result)

`

Output

Number is between 2 and 7

How to Avoid Indentation Errors

To minimize indentation-related issues in Python, it is important to follow consistent coding practices: