In this programming challenge, you will write a program to calculate and save/display student letter grades. Create a dictionary where the key is the name of a student and the value is a list of the student's grades. Drop the lowest grade from each student's grades. Display to the console AND write to a file a list of the student names and their corresponding letter grades: The letter grade should be calculated from the average of the student's grades (excluding the grade that was dropped):
Average 90-100: A
Average 80-89.99:B
Average 70-79.99: C
Average 60-69.99: D
Average below 60: F
Your program should work for data files with a varying number of students and varying numbers of grades per student. Example
David | 88 | 75 | 90 | 86 | 80 | 94 |
Mary | 65 | 98 | 92 | 97 | 86 | 85 |
Caitlin | 80 | 84 | 82 | 88 | 86 | 0 |
Jonah | 75 | 70 | 74 | 83 | 86 | 78 |
Rebecca | 55 | 62 | 50 | 0 | 64 | 60 |
Output:
David | B |
Mary | A |
Caitlin | B |
Jonah | C |
Rebecca | F |
Solution:
def calc_grade(marks):
if marks >= 90:
return 'A'
elif marks >= 80:
return 'B'
elif marks >= 70:
return 'C'
elif marks >= 60:
return 'D'
return 'E'
student = {}
# Reading the data from text file
with open('data.txt') as txt_file:
data = txt_file.readlines()
# Putting the data into dictionary
for line in data:
stud = line.split(' ')
student[stud[0]] = [int(marks) for marks in stud[1:]]
# Removing least grade of each student
for stud in student:
marks = student[stud]
min_marks = min(marks)
min_ind = student[stud].index(min_marks)
del student[stud][min_ind]
# Calculating Letter Grade of each student
grades = {}
for stud in student:
total_marks = sum(student[stud]) / len(student[stud])
grade = calc_grade(total_marks)
grades[stud] = grade
# Printing calculated letter grades to the console
for stud in grades:
print(stud + '\t\t' + grades[stud])
# Writing the result out to a file
with open('output.txt', mode='w') as txt_file:
for stud in grades:
txt_file.write(stud + '\t\t' + grades[stud] + '\n')