Indentation in Python | Why does Python use indentation

What is Indentation?

Indentation is nothing but the space at the beginning of a code line. In other programming languages, like C++, Javascript, etc., the Indentation is just for the readability of code while in Python, Identation is mandatory otherwise the code will throw IdentationError.

In Python, Indentation is used in various cases like while defining the inner statement of a function, inside if else statement, and inside for and while loop. You can see all of these in the below codes.

Identation in Python

Indentation in function:

def add(a,b):
    return a+b

This is a simple function for adding two numbers. Here you can see in the next line of the code, we have taken some spaces, this is Indentation. This is necessary otherwise it will throw IndentationError. The space should be of atleast one step. But you can take more than one space to make your code look more readable.

Indentation in If else statements :

a = 200
b = 33
if b > a:
   print("b is greater than a")
elif a == b:
   print("a and b are equal")
   print("a is greater than b")

Indentation in for and while loops:

for x in range(6):

i = 1
while i < 6:
   i += 1

Why do we use Indentation in Python?

Since there are no begin/end brackets there cannot be a disagreement between the grouping perceived by the parser and the human reader. Occasionally C programmers will encounter a fragment of code like this:

if (x <= y)


Only the x++ statement is executed if the condition is true, but the indentation leads you to believe otherwise. Even experienced C programmers will sometimes stare a long time at it wondering why y is being decremented even for x > y.

Because there are no begin/end brackets, Python is much less prone to coding-style conflicts. While nobody uses a coding style that doesn’t use indentation, in languages like C there are many different ways to place the braces.

If you’re used to reading and writing code that uses one style, you will feel at least slightly uneasy when reading (or being required to write) another style.

Many coding styles place begin/end brackets on a line by themself. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program.

Ideally, a function should fit on one screen (say, 20-30 lines). 20 lines of Python can do a lot more work than 20 lines of C. This is not solely due to the lack of begin/end brackets — the lack of declarations and the high-level data types are also responsible — but the indentation-based syntax certainly helps.

Leave a Comment