Home > Software engineering >  How is this nested loop being evaluated? [closed]
How is this nested loop being evaluated? [closed]

Time:09-25

(Python3) How are the values 0,6,18,36 calculated?

stop = 20
result = 0

# Start nested loop
for a in range(5):
    for b in range(4):
        result  = a * b
    print(result)
    if result > stop:
        break

---OUTPUT---
0
6
18
36

CodePudding user response:

First a loop where a equals zero, result keeps being incremented by 0 times 1, then times 2...times 4 essentially 0.

Second loop, a equals 1 and result is being incremented by 1 times 0, times 1, times 2 and times 3. Total 6.

Third loop result incremented by 2 times 0 then times 1...times 3. Total increment is 12 in addition to 6 makes 18.

Last loop, same thing with 3. result is incremented by a total of 18 and becomes 36. At which point, after printing it because it is greater than stop = 20.

CodePudding user response:

Let python tell you

stop = 20
result = 0
for a in range(5):
    for b in range(4):
        print(f'next calc: {result}  = {a} * {b}')
        result  = a * b
        print(f'       ==> {result}')
    print(result)
    if result > stop:
        break

Output

next calc: 0  = 0 * 0
       ==> 0
next calc: 0  = 0 * 1
       ==> 0
next calc: 0  = 0 * 2
       ==> 0
next calc: 0  = 0 * 3
       ==> 0
0
next calc: 0  = 1 * 0
       ==> 0
next calc: 0  = 1 * 1
       ==> 1
next calc: 1  = 1 * 2
       ==> 3
next calc: 3  = 1 * 3
       ==> 6
6
next calc: 6  = 2 * 0
       ==> 6
next calc: 6  = 2 * 1
       ==> 8
next calc: 8  = 2 * 2
       ==> 12
next calc: 12  = 2 * 3
       ==> 18
18
next calc: 18  = 3 * 0
       ==> 18
next calc: 18  = 3 * 1
       ==> 21
next calc: 21  = 3 * 2
       ==> 27
next calc: 27  = 3 * 3
       ==> 36
36
  • Related