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.

    Next, a = 1, result = 0.

    Finally, a = 2, result = 6.