Indentation in Python
Overview
Indentation in Python is simply the spaces at the beginning of a code line. Indentation in other languages like C, C++, etc., is just for readability, but in Python, the indentation is an essential and mandatory concept that should be followed when writing a python code; otherwise, the python interpreter throws IndentationError.
What is Indentation in Python
Indentation is the leading whitespace (spaces or/and tabs) before any statement in Python. The reason why indentation is important in python is that the indentation serves another purpose other than code readability. Python treats the statements with the same indentation level (statements with an equal number of whitespaces before them) as a single code block. So whereas in languages like C, C++, etc. a block of code is represented by curly braces { }, in python a block is a group of statements that have the same Indentation level i.e same number of leading whitespaces.
Below are some of the observations that can be made from the above figure:
- All the statements which are on the same level of Indentation(Same no of whitespaces before them) belong to a single block, so from the above diagram, statements in line 1, line 2, and line 7 belong to a single block, and the block has the zero or lowest level of indentation. Statements 3 and 5 are indented one step, forming another block at the first level of indentation. Similarly, statements 4 and 6 are indented two steps, so they together form another block at the second level of indentation.
- Below the line 2 statement, which is an if statement, statements 3 and 5 are indented one step; hence, they belong to a single block. And since line 2 is an if statement, the block indented below the first if forms the body of second if. So here, the body of the if statement at line 2 includes all the lines that are indented below it, i.e., lines 3,4,5 and 6.
- Now that we know that statement at line numbers 3,4,5 and 6 forms the body of the if statement at line 2. Let us understand the indentation for them. Statements at 3 and 5 are uniformly indented, so they belong to a single block (block2 from the interpretation), and they will be executed one by one.
- Statement at line 4 makes up the body of the if statement at line 3, as we know any statements that are indented below an if form the body of if statement, similarity the statement at line 6 makes up the body of else statement at line 5.
- This is how the indentation helps define the blocks and also to identify to which statements the block belongs.
Execution
- The execution starts at line 1 followed by the statement at line 2; if the condition is evaluated and in case it returns true, then control goes inside the body of the if statement, which brings statements 3,4, 5, and 6 to the picture.
- Now, the statement at line 3 is executed, and if the condition is evaluated, in case it returns true, then line 4 is executed, after which control goes to line 7. If the condition at line 3 returns false, then control goes to another statement that is line 5, and then line 6 is executed, followed by the statement at line 7.
- In case condition at line number 2 returns false, the control skips lines 3, 4, 5, and 6 and goes to the statement at line 7.
Examples
Example 1: Below is an example code snippet with the correct indentation in python.
Code:
Output:
Explanation:
- The name variable gets assigned to Rahul in the first statement
- Now the statement if name == ‘Rahul’: is evaluated, it returns true, so it executes the body of the if, which is the indented next two statements below the if statement. The two statements inside the body are print(‘Welcome Rahul..’) and print(‘How are you?’) and they get executed.
- Once the statement gets executed the else part is skipped and control goes to the next statement which is print(‘Have a great day!’), which is executed.
- In this program, the statements inside the bodies of if and else are indented.
Example 2: Below is an example code snippet with correct indentation.
Code:
Output:
Explanation:
- Variable i is initialized to 1 in the first statement
- Now while(i <= 6) is executed which is true, so the body of the while is executed. The body of the while is all the statements that are indented below the while loop.
- So print (“Value is” + str(i)) and i = i + 1 are executed.
- This process is repeated till the while condition returns false.
- Here the statements print (“Value is ” + str(i)) and i = i + 1are uniformly indented to form a block and also the body of the while statement.
How to indent your python code
Let us walk through how to indent a python code by taking a simple example.
Example: Check if a given number is even or odd and if it’s zero print neither even nor odd
Let us discuss the approach step-wise:
- The first step is to assign an integer variable with the input number.
- Write an if-else block to check if the input number is 0,
- If It is not zero, Inside the if block, write another if-else (inner if-else) block to check the condition number % 2 == 0(This is the even check for a given number)
- If the condition number % 2 == 0 is true, print that the number is even.
- If the condition number % 2 == 0 is false, then the number is odd in the else block print.
- If It is not zero, Inside the if block, write another if-else (inner if-else) block to check the condition number % 2 == 0(This is the even check for a given number)
- If the number is zero, Inside the outer else block print that the given number is neither even nor odd.
Code:
Output:
Explanation:
- At the first level of the indentation line, numbers 1, 3, and 8 belong to a single block.
- Execution starts from line 1 and is followed by line 3.
- At line 3, the if condition is evaluated, and since the number != 0 returns True, control goes inside the if condition, which is the indented block of statements below the if at line 3.
- Inside the if block
- Line no 4 and 6 are on the same indentation level( Second indentation level), so they belong to a single block
- The if condition at line no 4 is evaluated, and since 50 % 2 == 0 returns True, control goes inside the if statement at line 4. So control goes to line 5, and the print statement is executed.
- Control late skips the else block inside the inner if-else and the else block of the outer if-else and goes to the statement below line 9.
How to avoid python indentation errors
1. Python will throw an indentation error if you skip the indentation. For Example, the below code would throw IndentationError: expected an indented block error:
Wrong Indentation(Error):
With Correct Indentation:
2. The number of whitespaces in indented code should be the same for the same block of code. Otherwise, Python will throw IndentationError: unexpected indent.
Wrong Indentation(Error):
With Correct Indentation:
3. Indentation on the first line of code is not allowed. Python will throw IndentationError: unexpected indent.
Wrong Indentation(Error):
With Correct Indentation:
4. Indented statements should have an attaching statement; for instance, all the statements indented below form a block and belong to the if statement. This is applicable for while, for, functions, classes, etc in python. The below example makes this point clear.
Wrong Indentation(Error):
The above program will throw the “IndentationError: unindent does not match any outer indentation level” error because the last print statement, which is indented, does not match with any other indentation(no attaching outer statement). In the program, hence this will throw an error.
Correct Indentation:
Here the last print statement’s indentation matches with the indentation of the print statement below if block. Hence here, the outer attaching statement is the if statement.
Python Indentation Rules
- Python uses four spaces as default indentation spaces. However, the number of spaces can be anything; it is up to the user. But a minimum of one space is needed to indent a statement.
- The first line of python code cannot have an indentation.
- Indentation is mandatory in python to define the blocks of statements.
- The number of spaces must be uniform in a block of code.
- It is preferred to use whitespaces instead of tabs to indent in python. Also, either use whitespace or tabs to indent; intermixing of tabs and whitespaces in indentation can cause wrong indentation errors.
Benefits of Indentation in Python
- Indentation of code leads to better readability, although the primary reason for indentation in python is to identify block structures.
- Missing { and } errors that sometimes popup in C, C++ languages can be avoided in python; also the number of lines of code is reduced.
Disadvantages of indentation in Python
- Code must be carefully indented with proper number of whitespace and ensure that whitespaces' uniformity is maintained in a single block. If the number of lines in python code is huge, sometimes this can become tedious if the indentation is corrupted by chance.
- Without the use of good editors/Ide’s that help with the indentation, writing a python code, especially huge lines of code, is sometimes a tedious task because, for each line, we should make a type in the indentation as well.
Conclusion
- Python indentation is something that is a foundation concept for any new python programming and understanding.
- Indentation is mandatory in python to define the blocks of statements.
- It is preferred to use whitespaces instead of tabs to indent in python.
- Python uses four spaces as default indentation spaces.