What Is Nested Loops ?

A nested loop is a loop inside another loop. Python allows you to place any type of loop inside another loop, such as a for loop inside another for loop, or a while loop inside another while loop.

Syntax of Nested Loops

In Python, the loop that contains another loop is called the outer loop, and the loop inside it is called the inner loop. The inner loop executes completely from start to finish for every single iteration of the outer loop.

A. Nested for Loop Syntax

for outer_variable in outer_sequence:
    # Code block of the outer loop
    
    for inner_variable in inner_sequence:
        # Code block of the inner loop
        # This runs fully for every outer_variable iteration
        pass
        
    # More code block of the outer loop (optional)

B. Nested while Loop Syntax

while outer_condition:
    # Code block of the outer loop
    
    while inner_condition:
        # Code block of the inner loop
        pass
        # Increment/decrement inner loop variable
        
    # Increment/decrement outer loop variable

Example 1: Basic Coordination Grid (Nested for)

This example demonstrates how variables change step-by-step. The inner loop finishes all its steps before the outer loop moves to the next item.

# Outer loop running 3 times
for i in range(1, 4):
    # Inner loop running 2 times
    for j in range(1, 3):
        print(f"Outer i = {i}, Inner j = {j}")
    print("--- End of Inner Loop Cycle ---")

Using the break Statement in Nested Loops

The break statement only terminates the loop it is currently inside. If a break is triggered inside an inner loop, only the inner loop stops immediately. The outer loop continues its regular execution.

Example: Finding a Target Product

Suppose we want to check pairs of numbers. If the product of i and j becomes 4, we stop searching that specific inner line.

for i in range(1, 4):
    print(f"Starting Outer Loop Row {i}")
    
    for j in range(1, 4):
        if i * j == 4:
            print(f"  -> Found i*j=4 at j={j}. Breaking Inner Loop!")
            break  # This stops the current inner loop execution
        print(f"  Inner j = {j} (Product: {i*j})")
        
    print(f"Finished Outer Loop Row {i}\n")

Using the continue Statement in Nested Loops

The continue statement skips the remaining code inside the current loop iteration and moves directly to the next cycle of that specific loop. Just like break, it only affects the loop it belongs to.

Example: Skipping Specific Combinations

Let's print item combinations but skip the process whenever the inner loop variable matches the outer loop variable (i == j).

for i in range(1, 4):
    for j in range(1, 4):
        if i == j:
            continue  # Skips the print statement for this specific combination
        print(f"Pair: ({i}, {j})")