Python - Nested Loops

Hello, aspiring programmers! Today, we're going to dive into the fascinating world of nested loops in Python. As your friendly neighborhood computer teacher, I'm excited to guide you through this journey. Trust me, by the end of this lesson, you'll be looping like a pro!

Python - Nested Loops

What are Nested Loops?

Before we jump into the deep end, let's start with the basics. Imagine you're organizing your closet. You go through each shelf (that's one loop), and for each shelf, you sort through all the items on it (that's another loop inside the first one). That's essentially what nested loops are in programming – loops within loops!

Python Nested for Loop

Let's start with the for loop, which is like a reliable old friend in the Python world.

Basic Structure

Here's the general structure of a nested for loop:

for outer_variable in outer_sequence:
    # Outer loop body
    for inner_variable in inner_sequence:
        # Inner loop body

Simple Example: Multiplication Table

Let's create a simple multiplication table to understand this better:

for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i} x {j} = {i*j}", end="\t")
    print()  # Move to the next line after each row

This code will output:

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

Let's break this down:

  1. The outer loop (for i in range(1, 6)) runs 5 times, representing the rows.
  2. For each iteration of the outer loop, the inner loop (for j in range(1, 6)) runs 5 times, representing the columns.
  3. We print each multiplication result, using end="\t" to add a tab space instead of a new line.
  4. After each row (outer loop iteration), we print an empty line to move to the next row.

Real-world Example: Seating Arrangement

Imagine you're a teacher (like me!) arranging seats for a class. Let's create a seating chart:

students = ["Alice", "Bob", "Charlie", "David", "Eve"]
rows = 3
seats_per_row = 2

seat_number = 0
for row in range(1, rows + 1):
    print(f"Row {row}:")
    for seat in range(1, seats_per_row + 1):
        if seat_number < len(students):
            print(f"  Seat {seat}: {students[seat_number]}")
            seat_number += 1
        else:
            print(f"  Seat {seat}: Empty")
    print()  # Empty line between rows

This will output:

Row 1:
  Seat 1: Alice
  Seat 2: Bob

Row 2:
  Seat 1: Charlie
  Seat 2: David

Row 3:
  Seat 1: Eve
  Seat 2: Empty

In this example:

  1. The outer loop iterates through each row.
  2. The inner loop assigns students to seats in each row.
  3. We use a seat_number variable to keep track of which student we're assigning next.
  4. If we run out of students, we mark the remaining seats as "Empty".

Python Nested while Loop

Now, let's meet the while loop's cousin – the nested while loop. It's like a watchful guard that keeps checking a condition.

Basic Structure

Here's how a nested while loop typically looks:

while outer_condition:
    # Outer loop body
    while inner_condition:
        # Inner loop body

Example: Number Pyramid

Let's create a number pyramid to see nested while loops in action:

row = 1
while row <= 5:
    col = 1
    while col <= row:
        print(col, end=" ")
        col += 1
    print()  # Move to the next line
    row += 1

This will output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Let's break it down:

  1. The outer while loop controls the number of rows (1 to 5).
  2. For each row, the inner while loop prints numbers from 1 to the current row number.
  3. We increment col inside the inner loop and row inside the outer loop.

Real-world Example: Inventory Check

Imagine you're managing a small store. You need to check your inventory regularly. Let's simulate this with nested while loops:

inventory = {
    "apples": 50,
    "bananas": 30,
    "oranges": 40
}

days = 1
while days <= 3:  # Check for 3 days
    print(f"Day {days} Inventory Check:")
    for fruit, quantity in inventory.items():
        while quantity > 0:
            print(f"Checking {fruit}...")
            quantity -= 10  # Simulate selling 10 units each check
            if quantity <= 20:
                print(f"Low stock alert for {fruit}! Only {quantity} left.")
                break  # Stop checking this fruit if stock is low
        inventory[fruit] = quantity  # Update inventory
    print(f"End of Day {days} Inventory: {inventory}\n")
    days += 1

This will output something like:

Day 1 Inventory Check:
Checking apples...
Checking apples...
Checking apples...
Low stock alert for apples! Only 20 left.
Checking bananas...
Low stock alert for bananas! Only 20 left.
Checking oranges...
Checking oranges...
Low stock alert for oranges! Only 20 left.
End of Day 1 Inventory: {'apples': 20, 'bananas': 20, 'oranges': 20}

Day 2 Inventory Check:
Checking apples...
Low stock alert for apples! Only 10 left.
Checking bananas...
Low stock alert for bananas! Only 10 left.
Checking oranges...
Low stock alert for oranges! Only 10 left.
End of Day 2 Inventory: {'apples': 10, 'bananas': 10, 'oranges': 10}

Day 3 Inventory Check:
Checking apples...
Low stock alert for apples! Only 0 left.
Checking bananas...
Low stock alert for bananas! Only 0 left.
Checking oranges...
Low stock alert for oranges! Only 0 left.
End of Day 3 Inventory: {'apples': 0, 'bananas': 0, 'oranges': 0}

In this example:

  1. The outer while loop simulates checking inventory for 3 days.
  2. We use a for loop to iterate through each fruit in the inventory.
  3. The inner while loop simulates checking and selling each fruit until it's low in stock or sold out.
  4. We use break to stop checking a fruit if its quantity drops to 20 or below.

Conclusion

Congratulations! You've just mastered the art of nested loops in Python. Remember, nested loops are powerful tools, but use them wisely. They can make your code run slower if not used efficiently.

As with all programming concepts, practice makes perfect. Try creating your own nested loop scenarios – maybe a chess board setup, or a weekly school schedule. The possibilities are endless!

Keep coding, keep learning, and most importantly, have fun with it! Until next time, this is your friendly neighborhood computer teacher signing off. Happy looping!

Credits: Image by storyset