0

I have written a code that collects student's assignment/exam results and puts into a list of student dictionary object. Within the code there is also a dictionary that consist of the weightage of each assignment or exam. This then allows me to calculate the weighted results. How can I implement error handling into this code so that an error can be raised if weights dictionary contains entries that don't match the ones stored in the student dictionary?

For example: Student Dict: A1, A2, A3 Weights: A1, E1 (Error is raised since E1 isn't present)

[Current code]

class Student:
# Part 1a: Creating student class
    def __init__(self, stud_dict):
        self.name = stud_dict['name']
        self.results = stud_dict['results'].copy()

# Part 2: Getting weighted result
    def get_weighted_result(self, weights):
        result = 0
        for key in weights:
            result += weights[key] * self.results[key]
        return result

# Part 1b: Converting student dictionary list to student object list
def dict_to_class_obj(stud_dicts):
    students = []
    for stud_dict in stud_dicts:
        students.append(Student(stud_dict))
    return students

#Test Section
stud_dicts = [
    {
        "name": "Fus Ro Dah",
        "results": {
            "assignment_1": 10,
            "assignment_2": 10,
            "examination_1": 10,
        }
    },
    {
        "name": "Foo Barry",
        "results": {
            "assignment_1": 1,
            "assignment_2": 2,
            "examination_1": 3,
        }
    },
]

# creating Student objects list
students = dict_to_class_obj(stud_dicts)
print(students[0].name)
print(students[0].results)
print(students[0].get_weighted_result({"assignment_1": 1.0, "examination_1": 9.0}))  
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    Have a look at https://docs.python.org/3/tutorial/errors.html. – jonrsharpe Nov 16 '20 at 15:17
  • `def get_weighted_result(self, weights): if weights.keys() != self.results.keys(): raise Exception("Weights do not match results") ... ` Or for a more precise error: `def get_weighted_result(self, weights): for item in self.results: if item not in weights: raise Exception("'{}' missing in weights".format(item)) result = 0 ...` – Dev Yego Nov 16 '20 at 15:26

1 Answers1

0

The general answer to this question is

if error_condition is True:
  raise Exception("Description of the problem")
Lachlan
  • 165
  • 1
  • 10