我正在尝试从codeacademy的课程开始自学Python,到目前为止,它一直没问题。然而,我在学生成为老师7/9遇到了障碍。我无法找到讨论此问题的帖子,但如果我错过了一个,请随时告诉我。
根据codeacademy我成功完成了这个练习,但我知道这个代码有问题。当我在repl.it中使用下面的代码时,get_average(student)会返回正确的值。我已经通过改变成绩来测试这一点,但确保 - 但get_letter_grade(得分)为每个学生返回“A”。我尝试使用允许的数字范围更具体(见下文),但我仍然遇到同样的问题。
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(numbers):
total = sum(numbers)
total = float(total)/len(numbers)
return total
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
studentaverage = (homework * .1 + quizzes * .3 + tests *.6)
return studentaverage
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
我还尝试稍微更改get_letter_grade(得分)功能以使其更具体/受限制(我可能会采用错误的方式;我对此非常陌生),如下所示:
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80 and score < 90:
return "B"
elif score >= 70 and score < 80:
return "C"
elif score >= 60 and score < 70:
return "D"
else:
return "F"
但如上所述,我有同样的问题:无论我如何改变他们的成绩,它都会为每个学生返回“A”。
非常感谢您分享的任何建议,见解,智慧等等!
谢谢!
答案 0 :(得分:0)
我尝试了上面的代码,它完全正常,没有任何更改。 也许如果你可以分享你调用函数的方式,我可以对你可能遵循的错误程序有所了解。下面附有代码的片段及其相应的输出。
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(numbers):
total = sum(numbers)
total = float(total)/len(numbers)
return total
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
studentaverage = (homework * .1 + quizzes * .3 + tests *.6)
return studentaverage
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
# To calculate the grades of each student
grade_tyler = get_letter_grade(get_average(tyler))
grade_lloyd = get_letter_grade(get_average(lloyd))
grade_alice = get_letter_grade(get_average(alice))
print(grade_lloyd)
print(grade_alice)
print(grade_tyler)
输出:
乙
A
C
此外,我还尝试单独调用方法,结果与预期一致。
grade_A = get_letter_grade(95)
grade_B = get_letter_grade(85)
grade_C = get_letter_grade(75)
grade_D = get_letter_grade(65)
print(grade_A)
print(grade_B)
print(grade_C)
print(grade_D)
输出:
A
乙
C
d