繁体   English   中英

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

[英]Finding sum of all numbers in list — python

我创建了一个使用输入分数的程序,将其添加到列表中,并使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM