如何使用while循环对数组求和?[Python]

2024-04-26 18:20:57 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试用一个while循环对数组求和,出现了一些问题。我得到了这种类型的错误:

总计=总计+索引[数字] TypeError:“int”对象不可下标

这是我的密码

numbers = [1,5,6,3,7,7,8]
index = 0
total = 0
while index <= len(numbers):
    total = total + index[numbers]
    index += 1

我应该得到的答案是37,使用while循环


Tags: 对象答案密码类型indexlen错误数字
3条回答

index[numbers] 更改为numbers[index]

更改<;=至<;和索引[数字]到数字[索引]

numbers = [1,5,6,3,7,7,8]
index = 0
total = 0
while index < len(numbers):
    total = total + numbers[index]
    index += 1

print(total)

试试这个代码

使用<;而不是<;=和数字[索引]而不是索引[数字]

可以使用sum()函数执行此操作。

numbers = [1,5,6,3,7,7,8]
total = sum(numbers)
print(total)

Ailrk提供的答案是正确的,我只想补充一点,在Python中,您可以使用sum(numbers)来查找数组的和

相关问题 更多 >