3.4 Nested Loops and Conditional Statements

In Python, nested loops and nested conditional statements allow you to create more complex control flows by placing one loop or conditional inside another. This enables you to iterate over multiple dimensions of data or evaluate conditions in a hierarchical way. However, you should use nested loops and conditionals carefully to keep your code readable and efficient.

In this section, we’ll explore how nested loops and conditionals work, provide practical examples, and cover common scenarios where these structures are useful.


3.4.1 Nested Loops

A nested loop occurs when you place one loop inside another. The inner loop runs completely every time the outer loop runs once. Nested loops are especially useful when dealing with multi-dimensional data, like lists of lists, matrices, or tables.

Syntax:

for outer_variable in outer_sequence:
    for inner_variable in inner_sequence:
        # Code for inner loop
    # Code for outer loop

3.4.1.1 Example: Nested for Loops

Let’s consider a simple example where we use nested for loops to iterate over a 2D matrix.

Example:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for value in row:
        print(value, end=" ")
    print()  # To print a new line after each row

Output:

1 2 3 
4 5 6 
7 8 9 

In this example:

  • The outer for loop iterates over each row of the matrix.
  • The inner for loop iterates over each value in the current row.

3.4.1.2 Example: Nested while Loop

You can also nest while loops to achieve similar behavior.

Example:

i = 0
while i < 3:
    j = 0
    while j < 3:
        print(f"i = {i}, j = {j}")
        j += 1
    i += 1

Output:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2

Here, the outer while loop controls the i variable, while the inner while loop controls the j variable. Each time the outer loop iterates once, the inner loop completes all of its iterations.


3.4.2 Nested Conditional Statements

Nested conditional statements involve placing an if, elif, or else block inside another conditional. This allows you to check multiple levels of conditions and handle more complex decision-making scenarios.

Syntax:

if condition1:
    if condition2:
        # Code if both condition1 and condition2 are True
    else:
        # Code if condition1 is True but condition2 is False
else:
    # Code if condition1 is False

3.4.2.1 Example: Nested if Statements

Let’s consider a situation where we check multiple conditions within each other.

Example:

x = 10
y = 5

if x > 5:
    if y > 3:
        print("x is greater than 5 and y is greater than 3")
    else:
        print("x is greater than 5 but y is not greater than 3")
else:
    print("x is not greater than 5")

Output:

x is greater than 5 and y is greater than 3

In this case:

  • The first if checks if x > 5.
  • If the first condition is True, the nested if checks if y > 3. Based on the result of the inner condition, different code is executed.

3.4.3 Combining Nested Loops and Conditionals

Nested loops and conditionals often work together to handle more complex scenarios, such as processing data structures with conditions.

Example: Filtering Data in a 2D List

Let’s say we want to print only the even numbers from a 2D list (a matrix).

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for value in row:
        if value % 2 == 0:
            print(value, end=" ")
    print()

Output:

2 
4 6 
8 

In this example:

  • The outer for loop iterates over each row.
  • The inner for loop iterates over each value in the row.
  • The if statement checks if the current value is even, and if it is, it prints the value.

3.4.4 Practical Use Cases

3.4.4.1 Example: Multiplication Table

A common use case for nested loops is generating multiplication tables.

for i in range(1, 6):  # Outer loop for rows
    for j in range(1, 6):  # Inner loop for columns
        print(f"{i * j:2}", end=" ")  # Format output with padding
    print()  # Print a new line after each row

Output:

 1  2  3  4  5 
 2  4  6  8 10 
 3  6  9 12 15 
 4  8 12 16 20 
 5 10 15 20 25 

3.4.4.2 Example: Checking Prime Numbers

Nested conditionals can be used to find prime numbers by checking if a number has any divisors.

for num in range(2, 11):
    is_prime = True
    for i in range(2, num):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(f"{num} is a prime number")

Output:

2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number

3.4.5 Avoiding Too Much Nesting

While nested loops and conditionals are powerful, overuse can make code difficult to read and maintain. Excessive nesting can also reduce performance, especially in deeply nested loops that result in many iterations. To avoid these issues:

  • Use functions to break down complex logic.
  • Refactor loops if the complexity is too high.
  • Use list comprehensions or other Python features that allow cleaner and more readable code.

Example of Refactoring a Deeply Nested Loop:

Instead of this deeply nested structure:

for i in range(10):
    for j in range(10):
        if i * j > 50:
            if i % 2 == 0:
                print(i, j)

You can refactor to reduce nesting:

for i in range(10):
    for j in range(10):
        if i * j > 50 and i % 2 == 0:
            print(i, j)

3.4.6 Summary

  • Nested loops allow you to iterate over multi-dimensional data structures. The inner loop runs completely for each iteration of the outer loop.
  • Nested conditional statements let you evaluate multiple conditions in sequence. Each if, elif, or else block can contain another conditional inside.
  • Combining nested loops and conditionals can solve complex problems, like processing data structures or filtering specific elements.
  • Be mindful of excessive nesting, as it can make code harder to read and maintain. Refactoring complex logic into functions or using simpler structures can help improve readability.

By mastering nested loops and conditional statements, you can handle complex data and logic more effectively in your Python programs, solving more advanced problems with ease.