Flow controls: Loops · 6 / 26 Theory

Nested loops

Inside a loop you can write another loop. For each turn of the outer loop, the inner one does all of its turns.

for i in range(1, 4):
    for j in range(1, 3):
        print(i, j)
# 1 1
# 1 2
# 2 1
# 2 2
# 3 1
# 3 2

Total inner turns: 3 × 2 = 6.

Multiplication tables

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}")

Writing on the same line: print with end

To draw rows you must avoid the line break of the inner print and add it at the end of each row:

for i in range(1, 4):
    for j in range(1, 6):
        print(i * j, end=" ")
    print()   # line break when the row ends
# 1 2 3 4 5
# 2 4 6 8 10
# 3 6 9 12 15

Hexadecimal table

With :02X a number is written in hexadecimal with two digits and capital letters:

for n in range(0, 16):
    print(f"{n:02X}", end=" ")
print()   # 00 01 02 ... 0F

break and continue in nested loops

A break only leaves the innermost loop it is in. If you need to leave both, use a flag variable or reorganize the code.

Mind the cost

Two nested loops of 1000 turns make a million iterations. If the program becomes slow, think whether you really need the second loop.

Practice with Hexadecimal table from 0 to 255 and Infinite multiplication tables.