Python Nested Loops

 

Nested Loops

We can use loops inside other loops, such types of loops are called as nested loops.

 

Example: nesting for loop in while loop


while (i<=3):
    for k in range(1, 4):
        print(i, "*", k, "=", (i*k))
    i = i + 1
    print()


Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

 

Example: nesting while loop in for loop

for i in range(1, 4):
    k = 1
    while (k<=3):
        print(i, "*", k, "=", (i*k))
        k = k + 1
    print()


Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9