I have the following for loop written to sum all numbers in a list. I'm aware there is a sum
function in python.
我有以下for循环写入来汇总列表中的所有数字。我知道python中有一个sum函数。
tot = 0
var = 5
for num in range(1, var + 1):
tot += num
print tot
When I try to intialise tot
within the for loop, it gives an incorrect answer: i.e.
当我尝试在for循环中初始化时,它给出了一个错误的答案:即
var = 5
for num in range(1, var + 1):
tot = 0
tot += num
print tot
Any reason for this? Please note, I'm a beginner in python.
有什么理由吗?请注意,我是python的初学者。
1 个解决方案
#1
1
In the loop, you reassign the value of tot
to zero. Thus, tot
will simply be var
in the last iteration.
在循环中,您将tot的值重新指定为零。因此,tot将在上一次迭代中简单地为var。
#1
1
In the loop, you reassign the value of tot
to zero. Thus, tot
will simply be var
in the last iteration.
在循环中,您将tot的值重新指定为零。因此,tot将在上一次迭代中简单地为var。