d = list(range(10, 20))
total5 = 0
v = 0
while d[v] > 0:
total5 += d[v]
v += 1
print(total5)
# what is the problem with this code?
这是用于打印从11到20的数字总和的代码
答案 0 :(得分:1)
首先,range
在第二个参数(不包括20)之前停止。因此,range(10, 20)
的返回值为numbers from 10 to 19
。
要计算总和,您可以按以下方式修改while语句。
d = list(range(10, 20))
total5 = 0
v = 0
while v < len(d):
total5 += d[v]
v += 1
print(total5)
答案 1 :(得分:0)
您可以在python中使用list函数的sum
来获取输出:
d = list(range(10, 20))
print(d)
total5 = 0
v = 0
print(sum(d))
在您不停止增加的过程中,必须有一个断点,如列表的长度,您可以继续增加。在您的计算机中,它将始终大于0,并且此错误表明索引超出范围意味着超出列表长度。