Nested loops
Sometimes, we need to loop inside the loop. Luckily, that’s possible; loops can be nested inside other loops. This is useful when working with multi-dimensional data, such as lists that are stored in a list.
Let’s create a simple multiplication table from 1 to 3. Here’s how we can do that with a nested loop:
for i in range(1, 4):
for j in range(1, 4):
product = i * j
print(f"{i} x {j} = {product}")
print("---")
And this is what will be output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---
So there’s a lot happening here! First, the outer loop (with i) runs from 1 to 3. Next, the inner loop (j) also runs from 1 to 3. In terms of flow, it goes like this: for each i, we loop through all j. And in that inner loop, we calculate the product and print it. Then, we move on to the next i, and loop through all of j again. And that...