Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么这个循环的结果是21?_Python_Loops - Fatal编程技术网

Python 为什么这个循环的结果是21?

Python 为什么这个循环的结果是21?,python,loops,Python,Loops,任何人都可以给我一个完整的例子,这个代码?如果我打印总计,为什么结果总计为21 ie当前的总和 end=6 total = 0 current = 1 while current <= end: total += current current += 1 print total 因为1+2+3+4+5+6等于21。为什么会如此神秘?您通常可以通过介绍一些基本的调试来弄清这类事情的真相。我在代码循环中添加了一个打印,这样您就可以看到每次迭代后发生的事情: end=6 to

任何人都可以给我一个完整的例子,这个代码?如果我打印总计,为什么结果总计为21 ie当前的总和

end=6
total = 0
current = 1
while current <= end:
    total += current
    current += 1

print total

因为1+2+3+4+5+6等于21。为什么会如此神秘?

您通常可以通过介绍一些基本的调试来弄清这类事情的真相。我在代码循环中添加了一个打印,这样您就可以看到每次迭代后发生的事情:

end=6
total = 0
current = 1
while current <= end:
    total += current
    current += 1
    print "total: ", total, "\tcurrent: ", current 

print total
为了总结此处发生的情况,total和current分别初始化为0和1,在第一个回路上,total使用total+=current设置,total等于total=total+current,即total=0+1,然后current增加1到2,因此在第一个回路之后,它们分别为1和2

在第二个循环中,total+=current将被评估为total=1+2,即上一个循环结束时的值,依此类推。

您期望得到什么? 1+2+3+4+5+6=21

以下是开始值和每个循环的值

total   0 -> 1 -> 3 -> 6 -> 10 -> 15 -> 21
current 1 -> 2 -> 3 -> 4 ->  5 ->  6 ->  7

为什么你认为结果不会是21?因为我认为要求和,我需要求和总数的结果,而不是电流的结果。你能给我一个解释吗?@Overnet你认为total+=current在做什么?但是把部分总数加起来会得到1+1+2+1+2+2+3+4+1+2+3+4+5+1+2+3+4+5+6。据我所知,这才是你真正想要的,但这是不一样的。谢谢。我知道。为了找到结果,我需要对电流求和,因为总+=电流?是真的吗?是的,我知道。但是我不明白为什么我要把当前的结果加起来,而不是总数。谢谢。我知道。为了找到结果,我需要对电流求和,因为总+=电流?是真的吗?@Overnet:total+=current在这个上下文中等同于total=total+current,所以在每次迭代中,你都要把current的值加到total中。是的,我知道。但这个结果的总和是因为存在写入总计+=电流?总计+=电流与总计=总计+电流相同。我希望这对你有帮助,谢谢。我知道。为了找到结果,我需要对电流求和,因为总+=电流?是真的吗?@Overnet对不起,我不完全清楚你在问什么,我已经更新了我的答案,并做了进一步的解释,希望能澄清问题。如果还有任何困惑,请告诉我。
total   0 -> 1 -> 3 -> 6 -> 10 -> 15 -> 21
current 1 -> 2 -> 3 -> 4 ->  5 ->  6 ->  7