I'm a beginner for coding. I'm struggling to make student grader which each student names would be corresponded to each grade averages and show total average score among students. This is my code :
Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]
list1 = [Ken,Hiro,Nick]
total_average = 0
for j in list1:
x = 0
count = 0
for i in j:
x += i
count += 1
average = x / count
print (round(average,2))
total_average += average
final_average = total_average / len(list1)
print (round(final_average,2))
and result is :
7.33
13.67
20.0
13.67
However, I actually want to make code which returns like :
13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}
How could I express like this ?
It would be greatly appreciated if you could explain the details !!
I would suggest another approach altogether. First, you store your names and grades in a dictionary:
grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}
Then, you loop over the dictionary and compute the average for each student and prepare to compute the global average:
averages = {}
sum_of_grades, number_of_grades = 0, 0
for name, marks in grades.items():
averages[name] = sum(marks) / len(marks) # simple arithmetic average
sum_of_grades += sum(marks)
number_of_grades += len(marks)
Finally, you compute the global average:
final_average = sum_of_grades / number_of_grades
Here is the complete code, where the computations are encapsulated in a function:
grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}
def compute_averages(grades):
averages = {}
sum_of_grades, number_of_grades = 0, 0
for name, marks in grades.items():
averages[name] = sum(marks) / len(marks)
sum_of_grades += sum(marks)
number_of_grades += len(marks)
final_average = sum_of_grades / number_of_grades
return averages, final_average
averages, final_average = compute_averages(grades)
for name, avg in averages.items():
print(name, round(avg, 2))
print('Final average', round(final_average, 2))
Try using dictionary instead of lists. Initialize the dictionary: students = {'Hiro': 0, 'Ken': 0, 'Nick': 0}
Then assign values based on the computed average: students = {'Hiro': 20.0, 'Ken': 13.67, 'Nick': 13.67}
print(students)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With