Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Simple Student Grade Management System with Classes

Python Implement a Simple Student Grade Management System with Classes

Document Object Reference Manual Python3 Examples

We will use Python classes to implement a simple student grade management system. This system will let us add students, record their grades, and compute each student's average grade.

Example

class

Student:

   

def

init

(

self

,

name

)

:

       

self

.

name

=

name

       

self

.

grades

=

[

]

   

def

add_grade

(

self

,

grade

)

:

       

self

.

grades

.

append

(

grade

)

   

def

average_grade

(

self

)

:

       

return

sum

(

self

.

grades

)

/

len

(

self

.

grades

)

if

self

.

grades

else

0

class

GradeManager:

   

def

init

(

self

)

:

       

self

.

students

=

[

]

   

def

add_student

(

self

,

name

)

:

       

self

.

students

.

append

(

Student

(

name

)

)

   

def

get_student

(

self

,

name

)

:

       

for

student

in

self

.

students

:

           

if

student.

name

==

name:

               

return

student

       

return

None

   

def

add_grade_to_student

(

self

,

name

,

grade

)

:

        student

=

self

.

get_student

(

name

)

       

if

student:

            student.

add_grade

(

grade

)

       

else

:

           

print

(

f

"Student {name} not found."

)

   

def

show_average_grades

(

self

)

:

       

for

student

in

self

.

students

:

           

print

(

f

"{student.name}'s average grade is {student.average_grade():.2f}"

)

Example usage

manager

=

GradeManager

(

)

manager.

add_student

(

"Alice"

)

manager.

add_student

(

"Bob"

)

manager.

add_grade_to_student

(

"Alice"

,

90

)

manager.

add_grade_to_student

(

"Alice"

,

85

)

manager.

add_grade_to_student

(

"Bob"

,

78

)

manager.

add_grade_to_student

(

"Bob"

,

82

)

manager.

show_average_grades

(

)

Code analysis:

  1. Student class: represents a student, holding the student's name and a list of grades.add_grade The method adds a grade, and theaverage_grade method computes the average grade.
  2. GradeManager class: manages all students.add_student The method adds a student, theget_student method looks up a student by name, theadd_grade_to_student method adds a grade for a specified student, and theshow_average_grades method displays the average grades of all students.
  3. Example usage section: create a GradeManager instance, add two students, add grades for each student, and finally display each student's average grade.

Output result:

Alice's average grade is 87.50
Bob's average grade is 80.00

Document Object Reference Manual Python3 Examples