Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of all the elements in a list within a class

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading