for range in range python

时间:2014-05-17 21:34:27

标签: python loops for-loop range python-2.x

为什么不打印5?它打印10?

tot = 0
for i in range(5):
    tot = tot + i
print tot

1 个答案:

答案 0 :(得分:5)

逐行循环,看看会发生什么:

tot =tot + i
0   = 0  + 0   <-- i = 0
1   = 0  + 1   <-- i = 1
3   = 1  + 2   <-- i = 2
6   = 3  + 3   <-- i = 3
10  = 6  + 4   <-- i = 4

最后,你得到tot为10,然后返回。

此更改将为您提供返回值5:

tot = 0
for i in range(5):
    tot = tot + 1
print tot

再次通过循环线:

tot =tot+ 1
1   = 0 + 1   <-- i = 0
2   = 1 + 1   <-- i = 1
3   = 2 + 1   <-- i = 2
4   = 3 + 1   <-- i = 3
5   = 4 + 1   <-- i = 4