Search code examples
pythonloopsnestedrangeaddition

Difficulty understanding nested loops with addition, range and print function


When I put this Python code with input 12, the answer is 0, 6, 18. I don't know how to calculate that and I keep visualizing it as code snippet 2, with the answers 0,0,1,3,6,6,8,12.

How does this loop work?

stop=int(input())
result=0
for a in range(5): 
  for b in range(4): 
    result += a * b
  print(result)
  if result > stop: 
    break 

What I calculate

stop=int(input())
result=0
for a in range(5): 
  for b in range(4): 
    result += a * b
    print(result)
  if result > stop: 
    break 

picture of my calculations


Solution

  • I'll walk you through your for a in range(5) loop.

    First, a = 0, result = 0.

    • This loops 4 times and result remains at 0 because 0 * b = 0
    • 0 is printed

    Next, a = 1, result = 0.

    • Result += 1x0 + 1x1 + 1x2 + 1x3
    • So result = 0 + 6
    • 6 is printed

    Finally, a = 2, result = 6.

    • Result += 2x0 + 2x1 + 2x2 + 2x3
    • So result = 6 + 12 = 18
    • 18 is printed
    • if result > stop evaluates to true so the loop is broken.