Home > Blockchain >  Sum of all the elements in a list within a class
Sum of all the elements in a list within a class

Time:01-22

I've created a class named StudentInfo which will get the name of the student, grade, and the age. For adding those info in a list I've created a list named student and then append those info in that list. Now I want to find the average of those students' grades, so I've created a function get_average.

How do I total the sum of the grade of n number of students and print it?

For adding the marks alone I've called the index of particular and then the student's grade. Instead of this how can I add all the students grade and find the average?

Here's the code:

class StudentInfo:
    def __init__(self,name,age,grade):
        self.studentname = name
        self.studentage = age
        self.studentgrade = grade
    def name(self):
        return self.studentname
    def age(self):
        return self.studentage
    def grade_1(self):
        return self.studentgrade


class Course:
    def __init__(self,name,maxstudents):
        self.nameofcourse = name
        self.maxstudents = maxstudents
        self.student = []

    def add_student(self,studentinfo):

        return self.student.append(studentinfo)
    def get_average(self):

        avg =  (self.student[0].studentgrade   self.student[1].studentgrade  
self.student[2].studentgrade)/len(self.student)
        return avg


a = StudentInfo('karthi',16,100)
a2 = StudentInfo('lol',16,99)
a3 = StudentInfo('oo',16,90)

b = Course('cs',3)
b.add_student(a)
b.add_student(a2)
b.add_student(a3)
print(b.get_average())
print(b.student[1].studentname)

CodePudding user response:

Rewrite get_average() as:

def get_average(self):
    if self.student:
        return sum(s.studentgrade for s in self.student) / len(self.student)

Note:

The function will implicitly return None if the student list is empty

CodePudding user response:

You could use for loops for that.

def get_sum(self):
    self.sum = 0
    for student in self.student:
        self.sum  = student.studentgrade

    print(self.sum)

Also If you want to get the average of N Number of students you can later just devide the sum throught the amount of students

self.avg = self.sum/len(self.student)
    
  • Related