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.
Example of Python Indentation
4.
How to Avoid Indentation Error in Python?
5.
Indentation rules in Python
6.
How do Indentation Errors Occur in Python?
7.
Consequences of mandatory indentation in Python
8.
Fixing Indentation Errors in Python
9.
Advantages of Indentation in Python
10.
Disadvantages of Indentation in Python
11.
Best Practices for Using Indentation in Python
12.
Frequently Asked Questions
12.1.
What is indentation in Python if statement?
12.2.
Should I use spaces or tabs for indenting the code?
12.3.
Are there any advantages of indentation?
13.
Conclusion
Last Updated: Aug 27, 2024

Indentation in Python

Author APURV RATHORE
1 upvote

Introduction

In Python, indentation is not just a matter of style—it's a core part of the language's syntax. Unlike many other programming languages that use braces or keywords to define code blocks, Python relies on indentation to indicate the structure and flow of the code. In this blog, we will explore more about Indentation in Python.

Indentation in Python

What is indentation?

Indentation in Python refers to the use of whitespace (spaces or tabs) to define the structure and hierarchy of the code. Unlike many programming languages that use curly braces {} or other delimiters to group statements, Python uses indentation to indicate which statements are part of a block of code. This indentation is crucial for defining code blocks such as loops, conditionals, functions, and classes.

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.

Example of Python Indentation

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

How to Avoid Indentation Error in Python?

  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.

How do Indentation Errors Occur in Python?

Indentation errors in Python occur when the code's whitespace structure is inconsistent or incorrect, leading to syntax errors or unintended behavior. These errors typically arise in the following scenarios:

  • Inconsistent Indentation: Mixing tabs and spaces within the same block can cause errors. Python requires a consistent use of either tabs or spaces for indentation throughout a file.
  • Incorrect Block Structure: Failing to properly align code blocks, such as the lines inside loops or conditionals, can lead to IndentationError or SyntaxError. Each block must be indented uniformly.
  • Unintended Indentation Levels: Adding extra or missing indentation levels can change the logic of the code. For instance, placing a statement outside the intended block due to incorrect indentation can lead to logic errors.
  • Mismatched Indentation Levels: Nested blocks must be consistently indented to reflect their hierarchy. Incorrect indentation levels in nested structures will cause errors and affect the code’s execution flow.

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.

Fixing Indentation Errors in Python

To fix indentation errors in Python, follow these steps:

  • Identify the Error: Check the error message for line numbers or areas where the indentation issue occurs. Python will typically point out where the inconsistency is detected.
  • Consistent Whitespace: Ensure that you use either spaces or tabs for indentation consistently throughout your file. The Python community generally recommends using 4 spaces per indentation level.
  • Align Code Blocks: Make sure all statements within the same block are indented to the same level. Check nested blocks to ensure they are correctly aligned relative to their parent blocks.
  • Use an IDE or Editor: Utilize an integrated development environment (IDE) or code editor that highlights indentation errors and helps maintain consistent indentation.
  • Convert Tabs to Spaces: If using spaces is preferred, many editors offer options to convert tabs to spaces automatically.

Advantages of Indentation in Python

  • Readability: Makes code more readable and easier to understand by visually representing code structure and hierarchy.
  • Simplicity: Reduces the need for additional delimiters, such as braces, making the code less cluttered and more straightforward.
  • Enforces Consistency: Encourages consistent code formatting practices, promoting uniformity across codebases and teams.
  • Immediate Error Detection: Errors related to indentation are caught early, prompting developers to correct structural issues before execution.

Disadvantages of Indentation in Python

  • Error-Prone: Improper indentation can lead to syntax errors or logical errors, which can be challenging to debug.
  • Requires Discipline: Developers must be vigilant about consistent indentation, especially when working in teams or with legacy code.
  • Mixed Tabs and Spaces: Handling files with mixed tabs and spaces can be cumbersome, leading to errors or formatting issues.
  • Tool Dependency: Some code editors or IDEs may not handle indentation consistently, which can cause issues if not configured properly.

Best Practices for Using Indentation in Python

  • Use Spaces Consistently: Stick to spaces (preferably 4 per indentation level) rather than tabs, as this is the widely accepted convention in the Python community.
  • Configure Your Editor: Set up your text editor or IDE to handle indentation automatically and to convert tabs to spaces if needed.
  • Follow PEP 8 Guidelines: Adhere to the PEP 8 style guide for Python, which provides detailed recommendations for indentation and code formatting.
  • Check Indentation Regularly: Use tools or linters that check for consistent indentation and code style to avoid issues in large codebases.
  • Maintain Consistency: Ensure that all contributors to a project follow the same indentation practices to prevent formatting conflicts.

You can also read about the Multilevel Inheritance in Python.

Frequently Asked Questions

What is indentation in Python if statement?

In Python, indentation in an if statement determines the block of code that executes if the condition is true. All statements inside the if block must be indented to the same level to be considered part of that block.

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.

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. 

Conclusion

In this blog, we learned about indentation in Python. It is a fundamental aspect of its syntax, defining the structure and readability of the code. It replaces traditional braces or delimiters, offering a cleaner, more intuitive way to organize code blocks. Proper indentation enhances code clarity, making it easier to understand and maintain. 

Live masterclass