Python Code Example: nested for-loop

In the following program, a nested loop is used to check how often the loops are run through.

This code defines four variables: a, b, c1, and c2, and assigns values to a and b (5 and 7, respectively). c1 and c2 are both set to 0.

The code then enters a nested loop structure, where an outer loop (for i in range(20, a, -1)) runs 20 times, decrementing i by 1 each time. For each iteration of the outer loop, c1 is incremented by 1.

The inner loop (for j in range(0, b)) runs b times (in this case, 7 times), incrementing j by 1 each time. For each iteration of the inner loop, c2 is incremented by 1.

The code then checks if i is equal to j, and if so, it prints a message indicating how many times each loop has run, along with the values of c1 and c2. The message states that c1 represents the number of times the outer loop has run, and that c2 represents the number of times the inner loop has run (c1 multiplied by b).

It’s important to note that, in this code, i and j will never be equal, so the message will not be printed.

a, b, c1, c2 = 5, 7, 0, 0

for i in range(20, a, -1):
    c1 = c1 + 1
    for j in range(0, b):
        c2 = c2 + 1
        if i == j:
            print("How many times the loops are run?")
            print(
                "first loop: "
                + str(c1)
                + "\nsecond loop: "
                + str(c2)
                + " ("
                + str(c1)
                + " * "
                + str(b)
                + ")"
            )
Output
How many times the loops are run?
first loop: 15
second loop: 105 (15 * 7)