Introduction and Overview

Welcome, Python astronauts, to the intergalactic tour of nested loops in Python! Just like spaceships in formation, nested loops tackle layered problems. Our mission today is to understand the syntax and applications of nested loops, all of which will be enriched with a practical example.

Starry Dive into Nested Loops

Nested loops are simply loops within loops. They function much like stars and planets in the cosmos. Each celestial body (an outer loop star) has smaller bodies (inner loop planets) revolving around it. Similarly, for each iteration of an outer loop, an inner loop executes completely.

Syntax and Structure of Nested Loops in Python

Nested loops follow a hierarchical structure. For each iteration of an outer loop, an inner loop executes fully:

for outer_variable in outer_sequence:
    for inner_variable in inner_sequence:
        # Inner loop statements

Here's an example of a nested loop using Python's range() function. In this example, i represents different types of spaceships, and j represents various spaceship features:

for i in range(1, 4):  # Outer loop
    print('Start', i)
    for j in range(1, 4):  # Inner loop
        print(i, j)  # Prints spaceship type `i` and its attribute `j`
    print('End', i)

The code prints:

Start 1
1 1
1 2
1 3
End 1
Start 2
2 1
2 2
2 3
End 2
Start 3
3 1
3 2
3 3
End 3
Traversing the Cosmos with the While Loop in Python

Nested while loops also use an outer-inner structure:

while outer_condition:  # Outer loop condition
    while inner_condition:  # Inner loop condition
        # Inner loop statements

Here's an example with nested while loops:

i = 1  # Outer loop variable, representing spaceship types
while i <= 3: 
    print('Start', i)  # Start of each spaceship type iteration
    j = 1  # Inner loop variable, signifying spaceship features
    while j <= 3:  # Inner loop runs three iterations for each spaceship type
        print(i, j)  # Prints spaceship type `i` and its feature `j`
        j += 1  # Increase `j` by 1
    print('End', i)  # End of each spaceship type iteration
    i += 1  

The code prints:

Start 1
1 1
1 2
1 3
End 1
Start 2
2 1
2 2
2 3
End 2
Start 3
3 1
3 2
3 3
End 3
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal