Bytes

Indentation in Python (With Examples)

Last Updated: 7th December, 2024

This tutorial provided an overview of indentation in Python, a significant aspect of the language's syntax used to define code blocks. Python uses indentation to indicate the scope of code blocks such as functions, loops, conditionals, classes, etc. Let's understand the role and importance of indentation in python in detail.

Indentation in Python

What is Indentation in Python?

Indentation is significant in Python, a programming language known for its readability and simplicity indentation groups statements that belong together, such as a loop or a conditional statement. Python uses indentation instead of brackets to indicate blocks of code. Incorrect indentation could result in an error. ❌ Similar to a hopscotch game - hopping on one foot and after that the other, following the lines of the board, Python takes after the lines of code within the program. On the off chance that the lines of code were not enough indented, Python would not be able to execute the code within the correct order, and the program would not work as intended:

What is Indentation

For example, Let's write a simple program that prints the numbers from 1 to 10 using a for loop:

for i in range(111): 
    print(i)

In this program, the print(i) statement should be indented one level to the right of the for statement. This indentation indicates that the print(i) statement is part of the loop and should be executed for each value of I in the range. 🔁 To ensure proper execution of the program, it is crucial to include indentation before the print(i) statement.

for i in range(111):
print(i)

This program will also raise an IndentationError because the print(i) statement is not indented to the right of the for statement. Python cannot determine which statements are part of the block.

How to Intend Your Python Code?

If you're coding in Python, one of the most important things to remember is the proper indentation of your code. Good Python indentation is necessary to make your code readable and easy to understand, both for yourself and others who may read your code later.

  • So how can you ensure that your code is properly indented? To automatically indent your code, use a text editor with this feature already included. Some widely-used text editors that offer this feature are Sublime Text, Google Studio, Visual Studio Code, etc.
  • To ensure proper indentation, use the tab key to indent your code. This will help keep your code organized and easy to read. However, avoid over-indenting your code, as this can make it difficult to read.

How to Intend Your Python Code

For Example:

If we are writing a code if a particular number is even or odd:

number=20
if number!=0:
    if number%2==0:    
        print('Number is Even')
    else:
        print('Number is Odd')
else: 
    print('Number is neither even nor odd')

The above example shows that the second if-else statement is a code block under the first if-else statement because we have given a proper indentation for that code block.

How will the Above Code be Compiled?

  • It will check the first line to find 🔎 an integer variable🔢.
  • Then👉 , as soon as 🔜 it goes to the second line, it will find the if statement, and another if statement under the first statement will check 🧐 if the condition is satisfied.
  • If the second condition is unsatisfied, it will go to 🔙 the nested else statement.
  • But if the first if statement condition is not satisfied🚫, it will directly jump to the last else 👉🔚 statement as it is outside our code block and the first else statement after the if code block.

Python Indentation Rules with Examples

1. Indentation is Mandatory

  • All lines in a code block must be indented.
  • A block of code is typically associated with structures like if, for, while, def, class, etc.

Example:

if x > 0:
    print("Positive number"# Correctly indented
else:
print("Non-positive number"# Raises an IndentationError

2. Consistency in Indentation

  • Use the same amount of spaces or tabs within a block.
  • Mixing tabs and spaces leads to errors.

Example:

if True:
    print("Use 4 spaces")  # Consistent indentation
        print("Inconsistent indentation")  # Error: IndentationError

3. Recommended Indentation (PEP 8 Style Guide)

Example:

# PEP 8 Recommended Indentation
def greet():
    print("Hello!"# 4 spaces
    if True:
        print("Python is awesome!"# Nested block with 4 more spaces

4. Indentation for Nested Blocks

  • Indentation increases for each nested block to clearly define scope and hierarchy.

Example:

if condition1:
    print("Block 1")
    if condition2:
        print("Nested Block")
    print("Back to Block 1")
print("Outside all blocks")

5. Improper Indentation Raises Errors

  • Inconsistent or missing indentation will raise an IndentationError or TabError.

Example:

# Mixing tabs and spaces
def function():
\tprint("Tab used here"# Tab character
    print("Spaces used here"# Raises TabError

6. Blank Lines and Continuation Lines

  • Indentation is not required for blank lines.
  • For long lines broken across multiple lines, use hanging indentation or parentheses, and align properly.

Example:

# Hanging Indentation
result = (first_value
          + second_value
          + third_value)  # Aligned indentation

7. Comments Do Not Affect Indentation

  • Comments can be placed at any indentation level.

Example:

if True:
    # This is a comment
    print("Indented code")

Python Indentation Examples

1. Proper Indentation in if-else

Proper indentation ensures that blocks of code execute in the right context.

# Example
number = 5
if number > 0:
    print("Positive number")
else:
    print("Non-positive number")

Output:

Positive number

2. Improper Indentation

Incorrect indentation leads to a syntax error since Python relies on indentation to define code blocks.

# Example
number = 5
if number > 0:
print("Positive number")  # Improper indentation
else:
    print("Non-positive number")

Error:

IndentationError: expected an indented block

3. Nested Indentation

Nested blocks should have progressively deeper indentation to maintain structure.

# Example
number = 5
if number > 0:
    print("Positive number")
    if number % 2 == 0:
        print("Even number")
    else:
        print("Odd number")

Output:

Positive number
Odd number

4. Mixing Tabs and Spaces (Improper)

Mixing tabs and spaces within the same block leads to a TabError.

# Example
def greet():
\tprint("Hello!"# Tab used here
    print("Welcome!"# Spaces used here

Error:

TabError: inconsistent use of tabs and spaces in indentation

5. Indentation in Loops

Loops with proper indentation execute nested and outer loops without issues.

# Example
forin range(3):
    print(f"Outer Loop {i}")
    forin range(2):
        print(f"  Inner Loop {j}")
    print("Back to Outer Loop")

Output:

Outer Loop 0
  Inner Loop 0
  Inner Loop 1
Back to Outer Loop
Outer Loop 1
  Inner Loop 0
  Inner Loop 1
Back to Outer Loop
Outer Loop 2
  Inner Loop 0
  Inner Loop 1
Back to Outer Loop

6. Function with Correct Indentation

Correctly indented functions ensure proper execution of statements within their block.

# Example
def add_numbers(a, b):
    result = a + b
    print(f"Sum of {a} and {b} is {result}")
    return result

add_numbers(34)

Output:

Sum of 3 and 4 is 7

7. Indentation with Comments

Comments do not affect indentation and can be placed anywhere.

# Example
if True:
    # This is a comment
    print("Indented code")
    # Another comment
    print("Still indented")
print("Outside the block")

Output:

Indented code
Still indented
Outside the block

9. Multi-line Statements with Indentation

Multi-line statements require proper alignment for readability and execution.

# Example
total = (12 +
        34 +
        5)
print("Total:", total)

Output:

Total15

10. Indentation in Class Definitions

Classes with correct indentation ensure that methods and attributes are scoped properly.

# Example
class MyClass:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, {self.name}!")

obj = MyClass("Python")
obj.greet()

Output:

Hello, Python!

How to Avoid Indentation Error in Python?

Python Indentation Errors

What is Indentation Error in Python?

In Python, an indentation error occurs when spaces or tabs are not placed properly. Python uses indentation to group statements. If the interpreter finds issues with the spaces or tabs, it can halt execution. The error message indicates the line number and nature of the error. To fix it, check each line for proper indentation, ensuring 4 whitespaces for each level of indentation.

Incorrect Spacing

def my_function():
  print("Hello, Data Science Enthusiasts!")
   print("This line has an extra space.")
   
my_function()

In this example, the second print statement contains an additional space before it, which leads to an indentation error.

Mixing Spaces and Tabs

def my_function():
  print("Hello,Data Science Enthusiasts!")
        print("This line uses both spaces and tabs.")
        
my_function()

In this example, the second print statement has an indentation error because it uses a mix of spaces and tabs for indentation.

Inconsistent Indentation

def my_function():
    print("Hello, Data Science Enthusiasts!")
  print("This line has inconsistent indentation.")
  
my_function()

In this example, the second print statement has inconsistent indentation compared to the first print statement, which causes an indentation error.

Bad Block Indentation

def my_function():
    print("Hello, Data Science Enthusiasts!")
        print("This line is incorrectly indented.")
    print("This line is back to the correct indentation.")
    
my_function()

In this example, the second print statement needs to be indented correctly. This causes an indentation error for the entire block of code. To avoid most indentation errors in Python code, pay attention to these errors and follow the tips I mentioned earlier.

Best Practices for using Indentation in Python

Here are a few best practices for using indentation in Python: 🔎

  • Use consistent indentation throughout your code. 🤝
  • Use four spaces for indentation. ⌨️
  • Avoid mixing spaces and tabs. 🚫❌
  • Indent the code inside blocks consistently. 🧱
  • Use an editor that supports automatic indentation. 📝

Conclusion

In conclusion, space could be a principal perspective of Python utilized to demonstrate the structure of the code. Python's dependence on space has been questionable, but it is by and large considered a supportive highlight that creates code more readable and simpler to get it. By taking after the best hones for space, you'll be able to guarantee that your Python code is steady and simple to preserve.

Quiz

  1. Which of the following statements is true about Python's use of indentation?
    1. Indentation is optional in Python. 
    2. Python uses braces to indicate the structure of the code. 
    3. Indentation is used to group statements that belong together. 
    4. Indentation is used for decoration purposes only.

Answer: C: Indentation is used to group statements that belong together.

  1. What is the purpose of indentation in Python?
    1. To make code more complex
    2. To indicate the start and end of a block of code
    3. To reduce the number of lines of code required
    4. To make the code run faster

Answer: B. To indicate the start and end of a block of code.

  1. Why is proper indentation important in Python?
    1. It makes the code look more organized.
    2. It helps to improve code readability.
    3. It is a requirement in Python syntax. 
    4. It makes the code easier to debug.

Answer: B. It helps to improve code readability.

Module 2: Basics of Python ProgrammingIndentation in Python (With Examples)

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter