首页 > 解决方案 > 使用 for 循环打印总计

问题描述

我正在尝试通过代码 1 而不是代码 2 来获得 1、2、3、4 的总数。有人可以指出为什么代码 2 返回 4 而不是 10?

代码 1:

total = 0
for i in range(1,5):
    total = total + i

print(total)
10

代码 2:

total = 0
for i in range(1,5):
    newtotal = total + i

print(newtotal)
4

标签: python-3.xfor-loop

解决方案


这是因为在 code2 total 中没有更新,它总是为零,因为你将它初始化为 0 所以每次在 for 循环中我都会更新

newtotal = 0+1 = 1
next time
newtotal = 0+2 = 2
nex time
newtotal = 0+3 = 3
nex time
newtotal = 0+4 = 4

但是在代码 1 中,您每次都使用语句更新总的值

总计 = 总计 + 我

first time
total = 0+1 = 1
//now total is 1
next time
total = 1+2 = 3
next time
total = 3+3 = 6
next time
total = 6+4 = 10

因此答案 10


推荐阅读