为什么在下面的代码中将索引元素[0]的值22加到sum中?i
在这段代码中不是总是< 5
因为i = i -1
?
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
i -= 1
sum = sum + numbers[i]
print "The sum is: ", sum
为什么在下面的代码中将索引元素[0]的值22加到sum中?i
在这段代码中不是总是< 5
因为i = i -1
?
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
i -= 1
sum = sum + numbers[i]
print "The sum is: ", sum
i = 5
while (i != 0) --> i=5
i-=1 --> i=4
sum = sum+numbers[4]
while (i != 0) --> i=4
i-=1 --> i=3
sum = sum+numbers[3]
while (i != 0) --> i=3
i-=1 --> i=2
sum = sum+numbers[2]
while (i != 0) --> i=2
i-=1 --> i=1
sum = sum+numbers[1]
while (i != 0) --> i=1
i-=1 --> i=0
sum = sum+numbers[0]
while (i != 0) --> i=0 so it'll stop.
如您所见,将添加numbers[0]。
你可以重新安排你的代码(不改变它的行为):
while (i != 0):
sum = sum + numbers[i-1]
i -= 1
这清楚地表明numbers[0]
正在添加到总和。
但是,您不应该将其sum
用作变量名,因为它会覆盖(有用的)内置函数,例如,它可以让您更简洁地编写代码:
sum(numbers[1:]) #sum of everything in list except 1st element