Skip to content

A Comprehensive Guide to Indentation Rules for Code Blocks in Conditional Statements in Python

Updated: at 04:45 AM

Proper indentation is crucial in Python to correctly structure and organize code. Unlike other programming languages that use brackets or keywords to denote code blocks, Python relies solely on indentation to delimit blocks of code. This means that the number of spaces used for indenting code matters in Python. Incorrect indentation can lead to IndentationErrors or unintended program behavior.

In this comprehensive guide, we will cover indentation rules and best practices specifically for code blocks within conditional statements in Python. Conditional statements like if, elif, else, and while statements contain indented blocks of code that only execute when certain conditions are met. Understanding how to correctly indent these conditional code blocks in Python is key to writing programs that run as expected.

Table of Contents

Open Table of Contents

Overview of Indentation in Python

Python uses indentation levels to create code blocks and group related statements together. This is a key component of Python’s syntax.

For example:

# Block 1
if condition:
    # Block 2
    do_something()

    # Block 2
    do_something_else()

# Block 1
do_something_after()

This structure will run do_something() and do_something_else() only when condition is True, while do_something_after() will run either way after the if statement block.

Indentation Rules for Conditional Statements

Conditional statements like if, elif, else and while have specific indentation rules in Python for the code blocks under them.

If Statements

The if statement evaluates a condition and executes the indented code block below it if the condition is True.

if condition:
    # execute code block

Incorrect indentation:

# Missing indented block
if condition:

print("Incorrectly indented if statement")

This will throw IndentationError: expected an indented block because the print statement is not indented under the if.

Correct indentation:

if condition:
    print("Correctly indented block under if statement")

If/Else Statements

The else can be paired with an if statement to define an alternate block of code to run when the if condition is False.

if condition:
    # run if True
else:
    # run if False

Incorrect indentation:

if condition:
  print("Condition is True")

print("Outside if/else blocks")

else:
    print("Condition is False")

This will throw an IndentationError because the else is not lined up with the if properly.

Correct indentation:

if condition:
    print("Condition is True")
else:
    print("Condition is False")

print("Outside if/else blocks")

Elif Statements

The elif (short for else if) allows chaining multiple conditions to test.

if condition1:
    # run if condition1 is True
elif condition2:
    # run if condition1 is False and condition2 is True
else:
    # run if both conditions are False

Incorrect indentation:

if condition1:
    # do something
elif condition2:
   # do something else
 else:
    # do another thing

This is incorrect because the elif and else blocks are not lined up properly with the initial if statement.

Correct indentation:

if condition1:
    # do something
elif condition2:
    # do something else
else:
    # do another thing

While Loops

The while loop executes a code block repeatedly as long as a condition remains True.

while condition:
    # execute loop body

Incorrect indentation:

while condition:
print("Still in loop") # Loop body not indented

This will raise an IndentationError because the print statement is not indented under the while properly.

Correct indentation:

while condition:
    print("Still in loop") # Loop body now indented

Try/Except Blocks

try and except blocks handle and catch exceptions in Python. The except block must be indented properly to catch the exception from the try.

try:
    # run code
except:
    # handle exception

Incorrect indentation

try:
  # run code

except: # except not aligned with try
  print("Caught exception")

This will not catch the exception properly because the except is not aligned with the try.

Correct indentation

try:
  # run code
except: # except aligned with try
  print("Caught exception")

Indentation Best Practices

Beyond just following the indentation rules, here are some best practices for indentation in Python:

if condition1:
    # indented 4 spaces
    do_something()

elif condition2:
    # align with if
    do_something_else()

else:
    # align else
    final_thing()

Common Indentation Errors

Some common indentation errors include:

Python will raise various errors like IndentationError, TabError, or SyntaxError pointing to specific lines containing incorrect indentation.

Tools for Checking Indentation

Here are some useful tools for validating indentation:

Conclusion

Proper indentation is critical for Python’s use of whitespace to structure code. Indenting conditional statements correctly ensures code blocks execute as expected.

Follow these key indentation rules and best practices for conditional statements:

Adhering to indentation rules and styles, especially for conditional statements, will help write Python code that executes reliably according to the expected program flow.