+ 1

Wrong output

Hello everyone, I made this code to calculate the average grades for four students in the list called 'studentgrades;. I want the code to calculate the average grade for every student in the list. If i run it, it returns the average of the first two lists. but i want it to output the average for every single list I hope i made it clear, if its not please ask me. studentGrades = [[95, 92, 86],[66, 75, 54],[89, 72, 100],[34, 0, 0]] def average_per_student(studentGrades): res = 0 loopCount = 0 answer = [] for row in studentGrades: for item in row: loopCount = loopCount + 1 res = res + item average = res / loopCount answer.append(average) return answer def average_all_students(studentGrades): som = 0 answer = 0 loopCount = 0 for row in studentGrades: for item in row: som = som + item loopCount = loopCount + 1 total = answer + som #loopCount = loopCount + 1 antw = total / loopCount return antw print(average_per_student(studentGrades)) print(average_all_students(studentGrades))

16th Dec 2019, 9:23 PM
Abdelhakim Dahaman
Abdelhakim Dahaman - avatar
4 Antworten
+ 4
def average_per_student(studentGrades): answer = [] for row in studentGrades: res = 0 loopCount = 0 for item in row: loopCount = loopCount + 1 res = res + item answer.append(res/loopCount) return answer def average_all_students(studentGrades): res = 0 loopCount = 0 for row in studentGrades: for item in row: res = res + item loopCount = loopCount + 1 return res/loopCount
16th Dec 2019, 10:12 PM
Diego
Diego - avatar
+ 2
Abdelhakim Dahaman I did not fully read the code yet, but it seems to me that you have so many variables that really have no use. 1. Make a function that calculates the average of ONE student only. 2. Use it in a second function, that calculates the average of all students.
16th Dec 2019, 9:33 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
ok thanks, im gonna try that👍
16th Dec 2019, 9:39 PM
Abdelhakim Dahaman
Abdelhakim Dahaman - avatar
+ 1
sometimes......it's better to scrap it all start again:- def average_per_student(grades): aps = [] for marks in grades: aps.append(round(sum(marks)/len(marks), 2)) return aps def average_all_students(grades): average = 0 for marks in grades: average += sum(marks)/len(marks) return round(average/len(grades), 2) studentGrades = [[95, 92, 86], [66, 75, 54], [89, 72, 100], [34, 0, 0]] print(*average_per_student(studentGrades), sep=', ') print(average_all_students(studentGrades)) also..have a look at the statistics module for "mean" (average).
16th Dec 2019, 11:07 PM
rodwynnejones
rodwynnejones - avatar