Does a nested loop have to use the variable from the outer loop?


#1

Question

This exercise shows the nested loop using the variable from the outer loop. Does the nested loop always need to use the variable from the outer loop?

Answer

No, the nested loop doesn’t HAVE to use the variable from the outer loop. Although this is the most common application for a nested loop, it’s completely fine to have the nested loop perform some activity that does not involve the variable from the outer loop.

The following example shows two loops which both iterate over range() lists to produce a grid pattern. The nested loop operates independently of the outer loop variable.

for x in range(5):
    for y in range(5):
        print("X ",end='')
    print()