Skip to main content
 首页 » 编程设计

python之查找列表中所有数字的总和之python

2025年05月04日9傻小

我正在创建一个程序,它接受输入分数,将它们添加到列表中,然后使用 for 循环将它们全部加在一起显示总分。虽然遇到了一些问题。请检查一下..

scoreList = [] 
count = 0 
score = 0 
sum = 0 
while score != 999: 
    score = float(input("enter a score or enter 999 to finish: ")) 
    if score > 0 and score < 100: 
        scoreList.append(score) 
    elif (score <0 or score > 100) and score != 999: 
        print("This score is invalid, Enter 0-100") 
else: 
    for number in scoreList: 
        sum = sum + scoreList 
print (sum) 

请您参考如下方法:

问题很简单:

for number in scoreList: 
    sum = sum + scoreList 

如果你想在scoreList中添加每个数字,你必须添加number,而不是scoreList:

for number in scoreList: 
    sum = sum + number 

否则,您将尝试将整个列表添加到 sum,一遍又一遍,每个值一次。这将引发一个 TypeError: unsupported operand type(s) for +: 'int' and 'list'……但实际上,它可以做不到你想要什么。


一个更简单的解决方案是使用内置的 sum功能。当然,这意味着您需要一个不同的变量名,因此您不会隐藏函数。所以:

total_score = sum(scoreList)