难以理解具有加法、范围和打印功能的嵌套循环

Difficulty understanding nested loops with addition, range and print function

当我将此 python 代码输入 12 时,答案是 0、6、18。我不知道如何计算它,我一直将其可视化为代码片段 2,答案为 0, 0,1,3,6,6,8,12.

这个循环是如何工作的?

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

我算的

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

我将引导您完成 for a in range(5) 循环。

首先,a = 0,结果= 0。

  • 循环 4 次,结果仍为 0,因为 0 * b = 0
  • 0 被打印

接下来,a = 1,结果 = 0。

  • 结果 += 1x0 + 1x1 + 1x2 + 1x3
  • 所以结果 = 0 + 6
  • 6 被打印

最后a = 2, result = 6.

  • 结果 += 2x0 + 2x1 + 2x2 + 2x3
  • 所以结果 = 6 + 12 = 18
  • 18 被打印
  • if result > stop 计算结果为真,因此循环中断。