【问题标题】:Python how to sum a listPython如何对列表求和
【发布时间】:2016-09-30 17:10:34
【问题描述】:

我遇到了麻烦,因为我要求用户将 6 个数字输入到一个列表中,然后根据用户的输入对其进行总计和平均。这是我的HWK。请帮忙。

x = 0
list = []
while x < 6:
    user = int(input("Enter a number"))
    list.append(user)
    x = x + 1
numb = input("Do you want a total or average of numbers?")
numb1 = numb.lower
if numb1 == "total":

【问题讨论】:

  • sum(list),但请不要将您的列表命名为list,因为这是一个内置类型。
  • 不是说你有minimal reproducible example,但我敢打赌numb1 = numb.lower 不会像你想的那样做。

标签: python list sum average


【解决方案1】:

这是我的答案:

def numberTest():
    global x, y, z
    L1 = []
    x = 0 
    y = 6
    z = 1
    while(x < 6):
        try:
            user = int(input("Enter {0} more number(s)".format(y)))
            print("Your entered the number {0}".format(user))
            x += 1
            y -= 1
            L1.append(user)
        except ValueError:
            print("That isn't a number please try again.")
    while(z > 0):
        numb = input("Type \"total\" for the total and \"average\"").lower()
        if(numb == "total"):
            a = sum(L1)
            print("Your total is {0}".format(a))
            z = 0
        elif(numb == "average"):
            b = sum(L1)/ len(L1)
            print("Your average is {0}".format(round(b)))
            z = 0
        else:
            print("Please try typing either \"total\" or \"average\".")
numberTest()

我尝试了几次,我知道它有效。如果您对部分代码感到困惑,我将添加 cmets 并回答更多问题。

【讨论】:

    猜你喜欢
    • 2023-01-05
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多