Sign in

What is Indentation in Python and Why it is Important?

What is Python Indentation

Compilers/interpreters generally do not know the sequence in which they need to execute the statements in a piece of code. Hence, to make it easier, we divide the code into several blocks of code and indent it. This indentation helps them understand the order in which each block/statement should be executed.

Similarly, Python indentation is a way of telling the Python interpreter that a series of statements belong to a particular block of code. In languages like C, C++, Java, we use curly braces { } to indicate the start and end of a block of code. In Python, we use space/tab as indentation to indicate the same to the compiler.

How to Avoid Python Indentation Errors

Use either the space button or tab button to indent your code. If both are used interchangeably, the interpreter will not be able to interpret the code and hence throws an error.

If you have used only one among them, then check for consistency in the indentation. If you indented block code 1 with 4 spaces, then block code 2 has to be indented with 8 spaces and not anything less than that.

Finally, change your editor to make tabs and spaces visible and this will help you spot them easily.

Student. Currently pursing my B.Tech. in GVPCE(A)