我有这个作业问题,要求输入5个测验分数并计算等效的字母等级,然后求平均值并对其应用字母等级。
我目前有一个正在运行的程序,但我想看看是否有可能仅通过使用一组'if'语句来获得所有分数
def letter_grade(test1, test2, test3, test4, test5, average):
if test1 >= 90 and test1 <=100:
score1 = "A"
elif test1 >= 80 and test1 <= 89:
score1 = "B"
elif test1 >= 70 and test1 <= 79:
score1 = "C"
elif test1 >= 60 and test1 <= 69:
score1 = "D"
elif test1 < 60:
score1 = "F"
if test2 >= 90 and test2 <=100:
score2 = "A"
elif test2 >= 80 and test2 <= 89:
score2 = "B"
elif test2 >= 70 and test2 <= 79:
score2 = "C"
elif test2 >= 60 and test2 <= 69:
score2 = "D"
elif test2 < 60:
score2 = "F"
if test3 >= 90 and test3 <=100:
score3 = "A"
elif test3 >= 80 and test3 <= 89:
score3 = "B"
elif test3 >= 70 and test3 <= 79:
score3 = "C"
elif test3 >= 60 and test3 <= 69:
score3 = "D"
elif test3 < 60:
score3 = "F"
if test4 >= 90 and test4 <=100:
score4 = "A"
elif test4 >= 80 and test4 <= 89:
score4 = "B"
elif test4 >= 70 and test4 <= 79:
score4 = "C"
elif test4 >= 60 and test4 <= 69:
score4 = "D"
elif test4 < 60:
score4 = "F"
if test5 >= 90 and test5 <=100:
score5 = "A"
elif test5 >= 80 and test5 <= 89:
score5 = "B"
elif test5 >= 70 and test5 <= 79:
score5 = "C"
elif test5 >= 60 and test5 <= 69:
score5 = "D"
elif test5 < 60:
score5 = "F"
if average >= 90 and average <=100:
avgScore = "A"
elif average >= 80 and average <= 89:
avgScore = "B"
elif average >= 70 and average <= 79:
avgScore = "C"
elif average >= 60 and average <= 69:
avgScore = "D"
elif average < 60:
avgScore = "F"
return score1, score2, score3, score4, score5, avgScore
如果可能,我希望函数以更有效的方式返回字母分数。
答案 0 :(得分:2)
只需定义函数,然后使用它对每个测试和平均值进行评分:
def letter_grade(score):
if 90 <= score <= 100:
grade = "A"
elif 80 <= score <= 89:
grade = "B"
elif 70 <= score <= 79:
grade = "C"
elif 60 <= score <= 69:
grade = "D"
elif score < 60:
grade = "F"
return grade
tests = [50, 60, 65, 99, 25]
for test in tests:
print(f"score: {test}, grade: {letter_grade(test)}")
print("average grade:", letter_grade(sum(tests) / len(tests)))
输出:
score: 50, grade: F score: 60, grade: D score: 65, grade: D score: 99, grade: A score: 25, grade: F average grade: F