-9 python loops for-loop range python-2.x
为什么这不打印5?它打印10?
tot = 0
for i in range(5):
tot = tot + i
print tot
Run Code Online (Sandbox Code Playgroud)
逐行循环,看看会发生什么:
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
Run Code Online (Sandbox Code Playgroud)
最后你得到tot
10,然后你回来.
此更改将为您提供5的返回值:
tot = 0
for i in range(5):
tot = tot + 1
print tot
Run Code Online (Sandbox Code Playgroud)
再次通过循环线:
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
Run Code Online (Sandbox Code Playgroud)