Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is indentation
3.
Examples
4.
Avoiding indentation errors
5.
Indentation rules in Python
6.
Consequences of mandatory indentation in Python
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Indentation in Python

Author APURV RATHORE
1 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Python is one of the most popular and most widely used programming languages in the tech industry. Learning Python will improve your skills and provide you with a whole new set of career opportunities. 

One of the initial steps in learning Python is understanding what indentation is in Python and why it is crucial. 

What is indentation

In Python, the leading whitespace (spaces and tabs) before any statement is referred to as indentation.

Other languages such as C++, C, and Java use indentation for readability purposes, but indentation is an essential and mandatory feature in Python that must be followed while writing code; otherwise, the Python interpreter will throw an IndentationError.

The importance of indentation in Python is due to the fact that it serves a purpose other than code readability. Statements with the same indentation level (statements with the same number of whitespaces before them) are treated as Python’s single block of code. So, although a block of code in languages like C, C++, and others is represented by curly brackets({}), a block in Python is a group of statements with the same indentation level, i.e., the same amount of leading whitespaces.

For example, consider the following code. 

 

  • All statements on the same level of indentation (same number of whitespaces preceding them) belong to a single block. Hence, statements on lines 1, 2, and 7 belong to a single block, and the block has the zero or lowest level of indentation, as shown in the picture above. Statements 3 and 5 are indented by one step, forming a new block at the first level of indentation. Statements 4 and 6 are similarly indented two steps, creating a new block at the second level of indentation.
     
  • Statements 3 and 5 are indented one step more than the if statement on line 2, indicating that they are part of the same block. Because line 2 is an if statement, the block indented below it serves as the if's body. As a result, the body of the if statement at line 2 contains all the indented lines below it, namely lines 3,4,5 and 6.
     
  • The statements at 3 and 5 are equally indented, indicating that they are part of a single block and will be executed one by one. 
     
  • The body of the if statement at line 3 is made up by the statement at line number 4. Similarly, the statement at line 6 makes up the body of the if statement at line 5. 

 

Now let us see the execution flow of the above piece of code. 

  • Line 1 starts the execution, followed by the statement at line 2. The if condition is evaluated, and if it returns true, control moves to the body of the if statement, which includes statements 3,4, 5, and 6.
     
  • The statement on line 3 is now executed, and the if condition is evaluated; if it returns true, line 4 is executed, and control moves to line 7. If the if condition on line 3 returns false, control passes to the else statement on line 5, which executes line 6, followed by the statement on line 7.
     
  • If the condition on line 2 returns false, the control skips lines 3, 4, 5, and 6 and goes straight to the statement on line 7.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples

Example 1:

name = "ninja"
if name=="ninja":
    print("Welcome back ninja")
else:
    print("Welcome to the club ninja")
print("Enjoy!")

 

In the first line, the variable name is assigned to ninja. This is the first statement. 

Now the control reaches statement 2, which is the if statement. This if statement returns true, so the control reaches the body of the if statement. The indentation of the body of the if statement is one step more than the if statement. After the execution occurs, the else part is skipped, and the control reaches the last statement, which is print(“Enjoy!”). 

 

Example 2:

ptr = 2
while ptr*ptr<=100:
    if 100%ptr==0:
        print("One of the divisor of 100 is", ptr)
    ptr+=1

 

In the first line, the variable ptr is assigned the value 2. 

Now the condition in the while loop is verified. If it is true, the body of the while loop is executed. The body of the while loop has indentation one step more than the indentation of the while statement. Within the body of the while loop, there is an if statement. If the if statement verifies to be true, then the body of the if statement is executed (indented one more than the if statement). 

Then the variable ptr is incremented, and again the control falls back to the while loop. 

Also see, Swapcase in Python, and  Convert String to List Python

Avoiding indentation errors

  1. If you make any mistake in indentation, then Python throws an “IndentationError: expected an indented block” error.
if 1==2:
print("equal")
>>     print("equal")
    ^
IndentationError: expected an indented block.

 

2. Indented code should have the same number of whitespaces for each block of code. Otherwise, "IndentationError: unexpected indent" will be thrown by Python.

if( 1 == 2):
 print("Line 1")
     print("Line 2")

The correct indentation should be:

if( 1 == 2):
    print("Line 1")
    print("Line 2")

 

3. The indentation on the first line should be 0. Otherwise, "IndentationError: unexpected indent" will be thrown by Python.

You can try it on online python compiler.

Indentation rules in Python

  • Python's default indentation spaces are four spaces. On the other hand, the amount of space is entirely up to the user. However, a minimum of one space is required to indent a statement.
     
  • Indentation cannot be used on the first line of Python code.
     
  • In order to define blocks of statements in Python, indentation is required.
     
  • In a code block, the number of spaces must be equal.
     
  • In Python, whitespaces are preferred over tabs for indentation. Also, the indentation should be done with either whitespace or tabs; combining tabs and whitespaces in indentation might result in incorrect indentation issues.

Consequences of mandatory indentation in Python

There are some advantages as well as disadvantages due to the mandatory indentation rule in Python, 
Although the primary reason for indentation in Python is to identify block structures, it also improves readability. Missing and errors that can occur in c and c++ languages are also avoided in Python due to indentation, as well as the number of lines of code is reduced.

But there may be some downsides also. Code must be carefully indented with the appropriate amount of whitespace to maintain whitespace uniformity inside a single block. If the number of lines in python code is large, it might become laborious if the indentation becomes damaged.

You can also read about the Multilevel Inheritance in Python.

Frequently Asked Questions

  1. What is indentation in Python?
    In most cases, compilers/interpreters are unaware of how statements in a piece of code must be executed. As a result, we separate the code into several blocks and indent it. This indentation aids them in comprehending the order in which each block/statement should be executed.
     
  2. Should I use spaces or tabs for indenting the code?
    Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs. Python disallows mixing tabs and spaces for indentation.
     
  3. Are there any advantages of indentation?
    Proper indentation code improves code readability. Indentation is essential not in Python but in every other programming language for proper code readability. 

Key Takeaways

Congratulations on making it this far.

In this blog, we understood what indentation is in Python and why it is required. 

Check out this article - String slicing in Python, Fibonacci Series in Python

If you want to become proficient with Python programming, I suggest you take the Coding Ninjas Python Course, which will teach Python basics with Data Structures and Algorithms. 

Previous article
Python Syntax
Next article
Third Party Installer (pip) in Python
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass