I need help with python Classes exercise

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

I have been trying to solve the problem mentioned in the additional exercise since I feel that I am stuck. The problem in question here related to .get_average. here is my code

class Student: def __init__(self, name, year): self.name = name self.year = year self.grades = [] def add_grade(self, grade): if type(grade) == Grade: self.grades.append(grade) def get_average(self): self.score = 0 for i in self.grades: self.score += i return self.score / len(self.grades) class Grade: minimum_passing = 65 def __init__(self, score): self.score = score def is_passing(self): if self.score > self.minimum_passing: return True else: return False roger = Student("Roger van der Weyden", 10) sandro = Student("Sandro Botticelli", 12) pieter = Student("Pieter Bruegel the Elder", 8) pieter_grade = Grade(100) pieter.add_grade(pieter_grade) is_pieter_passing = Grade(100) print(is_pieter_passing.is_passing()) print(pieter.get_average())

Can someone please help me with my code. Thank you.

It might be wise to read the text that is now at the top of your post :wink:. Without a project or a description of your actual task you’ve left an awful lot of guesswork for everyone else. That should probably be changed.

Secondly, you seem to have some code that attempts to get an average? What’s wrong with it? Does it throw errors, does it just supply a value you did not expect? A little background goes a long way- How to ask good questions (and get good answers)

1 Like

The error is that you are trying to add an object and a number
in the get_average function
on this line: self.score += i (that’s line 14 in the Codebyte)

in the get_average function, you had:

self.score = 0
for i in self.grades:
  self.score += i

but self.grades seems to be a list of Grade objects, not a list of numbers
so the i in the for loop is a Grade object, not an int nor a float

In the Grade class, the number you want is stored in the score variable,
so to extract that number you need .score
i is an instance of Grade, so it would be i.score

So that line should actually be:
self.score += i.score

if you want to make the function even more flexible, you could check the type of i before adding it to self.score with an if statement, and add either i or i.score depending on what the type of i is.

1 Like