python-3.x - 使用 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
解决方案
这是因为在 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
推荐阅读
- api - _TypeError in call api flutter
- google-cloud-platform - 在 BigQuery 中存储日期/日期时间/时间/时间戳
- python - 卡住试图从“for”循环滚动两个列表框
- html - 为什么以错误的顺序生成 html 的这个元素?
- javascript - 两个 ObjectId 之间的 Mongoose 虚拟引用
- python - Python 看不到 Jenkins 参数化构建中设置的环境变量
- python - 使用 Beautiful Soup for Python 从网格表值中抓取文本问题
- blazor-client-side - Blazor Webassembly,自定义 http 响应标头
- javascript - 可汗学院算法 - 挑战:二分搜索“While 循环运行时间过长。”
- node.js - 快递,猫鼬:我想在一个对象内“req.body”,但我不知道该怎么做