Loops Inside Loops

A loop inside a loop

For every round of the outer loop, the inner loop runs all the way through.

Think of it like this: A clock: for every hour, the minute hand goes all the way round 60 times.

for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end="\t")
    print()

Output

1	2	3	
2	4	6	
3	6	9	

That's a small times table. \t is a tab, which lines the columns up.

Star patterns

Patterns are great practice for loops. Each row prints one more star than the last:

for row in range(1, 6):
    print("*" * row)

Output

*
**
***
****
*****

And the same with a real inner loop:

for row in range(1, 5):
    for star in range(row):
        print("*", end="")
    print()

Output

*
**
***
****

Tip: When a loop confuses you, trace it on paper: write down the value of each variable in every round.

HOME LEARN COMMUNITY DASHBOARD