Indentation in Python

Indentation plays a major role in Python. Let’s see with example.

Here is a sample code of if block without space:

This says to print “Hello from Python” whenever it executes and both the code statements are aligned to each other.

The Python interpreter will not know that the print statement should be executed whenever the if condition satisfies unless or until there is some space for the interpreter to understand.

At least, there should be one space for the interpreter to understand that the print statement actually falls under if block.

In the above code, interpreter would execute the statement 1 (i.e., if (true)) and recognize the if block and would anticipate for the code statements within if block. So, it would expect a space. If it wouldn’t find space, it would throw an error.

Below is the output, when the above code is executed.

It gives us an error saying, “Expected an indented block”.

Now let’s give one space and see what happens.

Code:                                                                                                                                                                                                                                           

Output:

I have given only one space as indentation. The same indentation needs to be followed throughout the if block.

For Example: As shown in the code sample, if there are multiple statements inside if block, all should follow the same indentation. If one statement has different indentation than the other statements, inside the same code block, it would throw an error.

Example:

In this code, second print statement’s indentation is not aligned with the first print statement. Hence, we get unexpected indent error.

Output:

If we want to print the second statement, outside the if block, we need to write it without any space as shown below:

Example:

Output:

Hope this gives a better overview on the indentation aspect in Python. Let’s continue with the other topic in next post.

Leave a comment

Design a site like this with WordPress.com
Get started