Python如何汇总列表

时间:2016-09-30 17:10:35

标签: python list sum average

我遇到了麻烦,因为我要求用户在列表中输入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":

1 个答案:

答案 0 :(得分:0)

以下是我的回答:

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()

我尝试了几次,我知道它有效。如果您对代码的某些部分感到困惑,我会添加注释并回答其他问题。