How To Use Indentation in Python

How To Use Indentation in Python

6 mins read980 Views Comment
Updated on Jan 12, 2023 12:44 IST

Indentation is basically the whitespace (spaces/tabs) that are inserted before a Python statement. In this article, we will learn how to indent your python code with the help of example. Later in the article, we will also discuss rules of indentation and the advantages of indentation in python.

2023_01_MicrosoftTeams-image-118.jpg

Python is arguably the most beginner-friendly language out there. Indentation in Python is one of its most distinctive features that make Python remarkably easy to interpret – both by the developer as well as the compiler. Indentation simply means that the Python code is written with spaces or tabs to differentiate between different blocks of code. In fact, indentation is a mandatory concept that needs to be kept in mind when writing Python code.

Today, we are going to discuss the rules of indentation in Python with examples. So, without further ado, let’s get started.

Table of Content

We will be covering the following sections:

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

Introduction

Indentation is basically the whitespace (spaces/tabs) that are inserted before a Python statement. Apart from the obviously improved code readability, the indentations also allow the Python compiler to interpret the code properly. Statements with the same indentation are considered to be a single block structure.

So, instead of using curly brackets {} like in languages such as C/C++, Python uses indentation to group its statements. Look at the diagram below for visual understanding.

How to Indent your Python Code

Let’s understand how the indentation works in Python using a basic if-else statement example.

The following program determines whether an integer input given by the user is odd or not:

 
value = int(input())
if(value != 0):
if(value % 2 == 0):
print("Even")
else:
print("Odd")
else:
print("You have entered zero")
Copy code

Outputs

1:

2023_01_image-30.jpg

2:

2023_01_image-31.jpg

3:

2023_01_image-32.jpg

Explanation

Let us understand how indentation helps in interpreting the above program:

  • At no indentation, we have
    • line 1 value = int(input()),
    • line 2 if (value != 0),
    • and line 7 else.

These lines belong to one block structure

  • Execution starts at the second line of code. Here, the condition value != 0 is evaluated, if the entered input is 7, the condition returns True, and the control goes to the inner if statement, at line 3 if (value % 2 == 0).
  • At line 3, we have the first level of indentation. Here, the condition value % 2 == 0 is evaluated and the control goes inside the inner if-else statement, which is at the second level of indentation.
  • Inside the inner if-else block
    • line 4 print (“Even”),
    • and line 6 print (“Odd”).

These lines belong to one block structure, that is the same indentation level (second).

The entered input is 7, which means that the if condition returns True, and the line 4 print statement is executed – “Even”, since 7 is an even number.

  • If the entered input is 0, the entire inner if-else block would’ve been skipped and the outer else statement at line 8 (first indentation level) would be executed – “You have entered zero” would be printed.

Python Indentation Examples

Below are two example code snippets with the correct indentation in Python for your understanding.

Example 1:

 
n = 13
while(n <= 20):
print("Value is " + str(n))
n = n + 1
Copy code

Output:

2023_01_image-33.jpg

Explanation:

  • Variable n is initialized to 13 in the first statement.
  • Now, the condition while(i <= 20) is checked. Since it is True, the body of the while loop is executed. The body of the while is basically all the statements that are indented under the while statement.
  • So, statements print(“Value is” + str(n)) and n = n + 1 are executed.
  • This process gets repeated until the while condition returns False.

Example 2:

 
name = 'Naukri Learning'
if name == 'Naukri Learning':
print('Welcome to Naukri Learning!')
print('What would you like to learn?')
else:
print('Hi! Would you like to polish your tech skills?')
print('We are Naukri Learning')
print('Have a great day!')
Copy code

Output:

2023_01_image-34.jpg

Explanation:

  • The variable name gets assigned to ‘Shiksha Online’ in the first statement.
  • Now the statement if name == ‘Shiksha Online’: is evaluated, it returns True, so the body of if-block is executed, that is, the indented two statements under the if statement.
  • Once the if statement gets executed the else part is skipped and control goes to the next statement, outside the if-else block, which is print(‘Have a great day!’). So, this is printed.
  • Thus, we can see that in the above snippet, the statements inside the if-else block are indented.
What is Programming What is Python
What is Data Science What is Machine Learning

Python Indentation Errors

Since Indentation is mandatory in Python, the compiler throws an IndentationError error if you skip indentation anywhere in the code. Let’s look at a few examples to help us avoid similar indentation errors while writing our Python codes.

Example 1: Indentation on the first line of code is not allowed

Wrong indentation:

 
number = 20
if(number > 0):
print("Positive number")
Copy code

Output

2023_01_image-35.jpg

Correct indentation:

 
number = 20
if(number > 0):
print("Positive number")
Copy code

Output:

2023_01_image-36.jpg

Example 2: Python will throw an indentation error if the indentation is skipped.

Wrong indentation:

 
number = 11
if(number >= 0):
print("Whole Number")
Copy code

Output:

2023_01_image-37.jpg

Correct indentation:

 
number = 11
if(number >= 0):
print("Whole Number")
Copy code

Output

2023_01_image-38.jpg

Example 3: One block structure should have the same number of whitespaces.

Wrong indentation:

 
number = 78
if(number >= 0):
if(number % 2 == 0):
print("Positive Even number")
print("Even Number")
Copy code

Output:

2023_01_image-39.jpg

Correct indentation:

 
number = 78
if(number >= 0):
if(number % 2 == 0):
print("Positive Even number")
print("Even Number")
Copy code

Output:

2023_01_image-40.jpg

Example 4: Indentations should be uniform.

Wrong indentation:

 
number = 10.8
if(number >= 0):
print("Positive number")
print("Thank you")
Copy code

Output

2023_01_image-41.jpg

The last print statement has an indentation that does not match with any other indentation (no attaching outer statement). Hence, the error.

Correct indentation:

 
number = 10.8
if(number >= 0):
print("Positive number")
print("Thank you")
Copy code

Output:

2023_01_image-42.jpg
Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Rules of Indentation in Python

  • Indentation in Python is compulsory to define a block of statements.
  • The indentation level (number of whitespaces) must be uniform in a code block.
  • The first line of code in Python should not have any indentation.
  • Intermixing whitespaces and tabs during indentation can lead to indentation errors in the code.
  • Whitespaces should be preferred over tabs to indent code lines in Python.
  • By default, Python uses four spaces as indentation. This can be altered by the programmer. But please note that a minimum of one space is required when indenting.

Benefits of Indentation in Python

Let’s summarize the pros of indentation in Python that we have discussed above:

  • Indentation helps the Python compiler identify code blocks.
  • It provides better readability to Python codes.
  • The code size also reduces considerably.
  • Fewer errors are encountered as commonly occurring errors such as missing brackets are not to be worried about.

But please keep in mind that:

  • Python codes need to be indented carefully with proper whitespaces – the number of spaces must be uniform and intermixing of tabs and spaces must be avoided. For larger Python programs, if this problem arises, it becomes a tedious task to find it in the program and fix it.
  • Using a good IDE/editor to write Python codes is a must to help with managing the indentations.

Conclusion

Hope this article was helpful for you to understand how mandatory indentation is in Python.

Top Trending Article

Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python

Interview Questions

Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio