【问题标题】:Finding sum of all numbers in list -- python查找列表中所有数字的总和 - python
【发布时间】:2013-10-01 22:36:51
【问题描述】:

我正在创建一个程序,该程序接受输入分数,将它们添加到列表中,并使用 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)

【问题讨论】:

  • 忽略该计数变量,此时它无用
  • “遇到一些问题”是什么意思?它会引发异常吗?给你某组输入的错误结果?还是什么?
  • 你可以只使用 sum() 内置,你用你的本地 sum 变量遮蔽它..
  • 你的程序不应该接受 0 或 100 的分数吗?因为现在按照你的条件设置方式,你的程序会忽略它们。
  • 作为旁注,while 上的 else 在这里真的没有必要。因为没有break,所以保证您每次都会点击它。如果您试图跳过用户没有给出任何分数的情况(通过在第一个提示符上输入999),那么没有充分的理由这样做;如果scoreList[]for number in scoreList: 是完全合法的,并且不会成功循环并且什么都不做。

标签: python list addition


【解决方案1】:

问题很简单:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2016-12-21
    • 2022-06-14
    • 2023-02-04
    • 2015-12-17
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多