Calling a method of the same class
Code review · Basic · §11.5 When you need a class
This class collects survey scores and calculates their average. It accepts only scores from 1 to 5. Inside average(), the line that calls the class's own total() method stops with an error. Fix one line so that the code prints 4.5. Grading also calls the methods with other scores.
Code to fix
class Survey:
def __init__(self, question):
self.question = question
self.scores = []
def add(self, score):
if 1 <= score <= 5:
self.scores.append(score)
def total(self):
result = 0
for s in self.scores:
result += s
return result
def average(self):
if len(self.scores) == 0:
return 0
return total() / len(self.scores)
s = Survey("Class satisfaction")
s.add(4)
s.add(5)
s.add(9)
print(s.average())Solve this problem in your browser
Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.