从测试中计算最终成绩

时间:2012-10-15 19:29:06

标签: python python-2.7 python-2.x

Lloyd = {
    "name":"Lloyd",
    "homework": [90,97,75,92],
    "quizzes": [ 88,40,94],
    "tests": [ 75,90]
    }
Alice = {
    "name":"Alice",
    "homework": [100,92,98,100],
    "quizzes": [82,83,91],
    "tests": [89,97]
    }
Tyler = {
    "name":"Tyler",
    "homework": [0,87,75,22],
    "quizzes": [0,75,78],
    "tests": [100,100]
    }

def average(value):
    avg=0
    items = len(value)
    for item in value:
        avg +=item 
    return avg/items

def getAverage(dictin):
    hw = average(dictin.get('homework'))
    quiz = average(dictin.get('quizzes'))
    tests = average(dictin.get('tests'))
    weighted_average = hw*.1 + quiz*.3 + tests*.6
    return weighted_average

def getLetterGrade(score):
    if score >=90:
        return "A"
    elif score < 90 and score >= 80:
        return "B"
    elif score < 80 and score >= 70:
        return "C"
    elif score < 70 and score >= 60:
        return "D"
    elif score < 60:
        return "F"
    else:
        return "No grades for you"

score = getAverage(Lloyd)
grade = getLetterGrade(score)
print grade

这样可以正常但我被告知,如果得分为89.5,则不起作用。我也试过了,但我无法找出问题所在。任何错误都是受欢迎的。

1 个答案:

答案 0 :(得分:5)

catch可能在average函数中,您将整数(avg)除以另一个整数(items)。由于两个操作数都是整数,因此Python也会将结果转换为整数,因此average函数永远不会返回小数分数。

有许多可能的解决方案:

  1. 在分割之前将其中一个操作数(avgitems)强制转换为浮点数;例如return float(avg)/itemsreturn (avg+0.0)/items

  2. avg从0.0而不是0开始 - 这可确保avg始终为浮点数。

  3. from __future__ import division添加到代码的最开头。这指示Python以Python 3.x方式使用除法并始终返回浮点数。

  4. 更新:根据MrGingerbear的评论,您可以考虑在getLetterGrade中向上或向下舍入分数。如果您从ceil模块导入floormath功能,则可以说ceil(score)将其四舍五入,floor(score)将其四舍五入,或{ {1}}将其四舍五入到最接近的整数。