TracksPractical Coding FoundationsControl FlowNested Loops and Conditions(9 of 11)

Nested Loops and Conditions

Sometimes one loop isn't enough. When you need to work with grids, tables, or compare every item against every other item, you'll reach for nested loops — loops inside loops.

How Nested Loops Work

When you put one loop inside another, the inner loop runs completely for each iteration of the outer loop. Think of it like a clock: the minute hand (inner loop) goes around 60 times for every hour the hour hand (outer loop) moves once.

# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end=" ")
    print()  # New line after each row

This produces:

1 2 3 
2 4 6 
3 6 9 

The outer loop (i) runs 3 times. For each value of i, the inner loop (j) runs 3 times. That's 9 total print statements — 3 × 3.

Conditions Inside Loops

A common pattern is filtering items as you loop through them. Instead of processing everything, you use an if statement to select only certain items:

numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
    if num % 2 == 0:
        print(num, "is even")

This checks each number and only prints the even ones. The condition acts as a gatekeeper, letting some iterations do work while others pass by silently.

Loops Inside Conditions

You can also flip this around — run a loop only when a condition is met:

should_count = True

if should_count:
    for i in range(5):
        print(i)

The entire loop only executes if should_count is True.

Managing Complexity

Nested structures are powerful but can quickly become hard to follow. A loop inside a loop inside a loop (three levels deep) is usually a sign you should step back and think about whether there's a simpler approach.

When writing nested loops, trace through the first few iterations by hand. Ask yourself: "What are i and j on the first pass? The second?" This mental walkthrough catches many bugs before they happen.

Tip: If your nested code is getting confusing, consider extracting the inner loop into a separate function. This makes each piece easier to understand and test.

See More

You need to be signed in to leave a comment and join the discussion