MadMeadyRevenge
MadMeadyRevenge

Reputation: 11

Why I get the ZeroDivisionError and how can I fix it?

Just starting out with OOP in Python, using a set of tutorials by 'Tech with Tim' Created a couple of classes for a student database - here is the relevant code.

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

    def get_grade(self):
        return self.grade

And

 def  get_avarage_grade(self):
    value = 0
    for student in self.students:
        value += student.get_grade()
    return value / len(self.students) # here

Plus

class Course:
def __init__(self, name, max_students):
    self.name = name
    self.max_students = max_students
    self.students = []

I think the issue is within the 2nd function. Why I get the ZeroDivisionError and how can I fix it?

Upvotes: 1

Views: 278

Answers (3)

Here:

return value / len(self.students) 

Your class needs a list whose values increases by one every time you do this:

value += student.get_grade() 

with a different student...

Upvotes: 0

Willem
Willem

Reputation: 11

The problem arises when self.students is an empty list: [ ]. len(self.students) will then return 0. This will give an error when you try to compute the average like you did. You need to decide what you want to return in the get_avarage_grade() method in case the self.students list is empty, for example some default_value.

def  get_avarage_grade(self):
  default_value = -1
  if len(self.students) == 0:
    return default_value
  value = 0
  for student in self.students:
    value += student.get_grade()
  return value / len(self.students) here

Upvotes: 1

Bernardo Lopes
Bernardo Lopes

Reputation: 126

Check if students is empty first, then do the operations if students is greater than 0.

def  get_avarage_grade(self):
    value = 0
    for student in self.students:
        value += student.get_grade()
    if len(self.students) > 0:
        return value / len(self.students)
    return value

Upvotes: 0

Related Questions