#python #function #return
#python #функция #Возврат
Вопрос:
У меня есть вопрос о домашнем задании с просьбой ввести 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
Я бы хотел, чтобы функция возвращала оценки букв более эффективным способом, если это возможно.
Ответ №1:
Просто определите функцию, а затем используйте ее для оценки каждого теста и среднего значения:
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