从列表中找到平均值

时间:2018-10-04 15:16:50

标签: python

这是我的代码

#Gets a list of numbers from user
def get_score():
    score_list = []
    keep_going = 'y'
    while keep_going == 'y':
        score = float(input('Enter a test score: '))
        while score < 0:
            print('Positive numbers only')
            score = float(input('Enter a test score: '))
        score_list.append(score)
        keep_going = input("More scores (y/n) ")
    return score_list

#Finding the average based on user's input 
def calculated_average():
    numbers_of_grades = float(input)
    score_list = [int(s) for s in score_list]
    average = sum(score_list) / len(score_list)
    return average

def main():
    score = get_score()
    average = calculated_average(score)

main()

我正在尝试根据用户的输入查找平均成绩,但似乎在计算平均分数时出现了问题。我似乎无法弄清楚如何获得score_list的总和。任何帮助表示感谢,谢谢!

2 个答案:

答案 0 :(得分:1)

修复了一些小错误,基本上,您只忘记将成绩列表解析为其他功能。它应该像这样工作:

#Gets a list of numbers from user
def get_score():

    score_list = []
    keep_going = 'y'

    while keep_going == 'y':

        score = float(input('Enter a test score: '))

        while score < 0:

            print('Positive numbers only')
            score = float(input('Enter a test score: '))

        score_list.append(score)
        keep_going = input("More scores (y/n) ")

    return score_list

#Finding the average based on user's input
def calculated_average(score_list):

    numbers_of_grades = len(score_list)
    score_list = [int(s) for s in score_list]
    average = float(sum(score_list) / len(score_list))

    return average

def main():

    score = get_score()
    average = calculated_average(score)
    print(average)

main()

答案 1 :(得分:1)

您只需将score传递到calculated_average,然后您就可以简单地return sum(x)/ len(x)

def calculated_average(x):
    return sum(x) / len(x)

def main():
    score = get_score()
    print(calculated_average(score))

main()
Enter a test score: 20
More scores (y/n) y
Enter a test score: 10
More scores (y/n) y
Enter a test score: 30
More scores (y/n) n
20.0