在python中使用def函数查找平均值和高于平均值

时间:2015-02-25 23:23:06

标签: python average

这是我的代码到目前为止。我不确定我是否在代码上做错了,因为平均值似乎是错误的。请帮我。谢谢

def enter_score ():
    results = []
    scores = int(input("How many results to enter? : "))
    for i in range(scores):
        student_name = input("enter student name: ")
        student_score = int(input("Please enter score for student " + student_name + " : " ))
        results.append(student_score)
        results.append(student_name)
        print(results)
    return results

def calc_average():
    total=0
    total=total+student_score
    average= total/scores
    print("the average is ", average)
    return
def above_average():
  above_average=0
  for i in range (scores):
    if results [i] > average:
        above_average = above_average + 1
        print(" the above average score is ", above_average)
    return above_average

enter_score()
calc_average()
above_average()

2 个答案:

答案 0 :(得分:1)

您正在制作一个包含分数和名称的列表results - 非常难以使用。你从enter_score返回该列表,然后完全忽略 - 你扔掉它!所以其他两个功能应该适用于一些魔法或稀薄的空气......?

显然,最后的整体流程必须是:

results = enter_score()
average = calc_average(results)
above_average(results_average)

calc_average必须以return average结尾。

通过将一个results调用替换为一个来更好地安排

results.append

results.append((student_score, student_name))

即,将其列为元组列表,而不是奇怪的数字和名称组合。

其他两个函数显然必须在该列表上循环(它们现在作为参数接收)来执行各自的工作。

所以:

def calc_average(results):
    total = 0
    for student_score, student_name in results:
        total=total+student_score
    average= total/float(len(results))
    print(average)
    return average

def above_average(average, results):
    above_average = 0
    for student_score, student_name in results:
        if student_score > average:
            above_average += 1
    print(" the number of above average scores is ", above_average)
    return above_average

答案 1 :(得分:0)

我已修复/修改了您的代码,以便它可以正常运行:

def enter_score ():
    results = []
    scores = int(input("How many results to enter? : "))
    for i in range(scores):
        student_name = input("enter student name: ")
        student_score = int(input("Please enter score for student " + student_name + " : " ))        
        results.append((student_name, student_score))
        print(results)
    return results

def calc_average(results):
    total=0
    for student_name, student_score in results:
        total=total+student_score
    average= total/len(results)
    print("the average is ", average)
    return average

def above_average(results, average_score):
    above_average_no=0
    for student_name, student_score in results:
        if student_score > average_score:
            above_average_no = above_average_no + 1
            print(" the above average score is ", above_average_no)
    return above_average_no

results = enter_score()
average_score = calc_average(results)

above_average_no = above_average(results, average_score)

我不会详细解释事情发生变化的原因和原因。留给你弄清楚。请注意,我尝试对您的代码进行最小的更改。许多事情都可以改进,例如计算sum等。希望这会有所帮助。