ICC-P Cours 13, exemple 2, School
Code:
from dataclasses import dataclass
from pprint import pprint
@dataclass
class Student:
id: str
name: str
grades: dict[str, float]
@dataclass
class School:
students: dict[str, Student]
def add_student(self, id: str, name: str) -> None:
if id in self.students:
print(f"Student with ID {id} already exists.")
return
student = Student(id, name, {})
self.students[id] = student
def record_grade(self, id: str, course: str, grade: float) -> None:
if id not in self.students:
print(f"Student with ID {id} not found.")
return
s = self.students[id]
if course in s.grades:
print(f"Warning: about to overwrite grade for {s.name} in {course}.")
s.grades[course] = grade
def display_student(self, id: str) -> None:
if id not in self.students:
print(f"Student with ID {id} not found.")
return
s = self.students[id]
print(f"Student: {s.name} ({s.id})")
if len(s.grades) == 0:
print(f" (no grades yet)")
return
for course, grade in s.grades.items():
print(f" {course}: {grade}")
school = School({})
# Adding students
school.add_student("S001", "Alice")
school.add_student("S002", "Bob")
pprint(school)
# Recording grades
school.record_grade("S001", "Analyse", 5.0)
school.record_grade("S001", "ICC", 6.0)
school.record_grade("S002", "Analyse", 5.0)
school.record_grade("S002", "ICC", 5.5)
school.record_grade("S002", "ICC", 6.0)
pprint(school)
# # Displaying student information
school.display_student("S001")
school.display_student("S002")
from pprint import pprint
@dataclass
class Student:
id: str
name: str
grades: dict[str, float]
@dataclass
class School:
students: dict[str, Student]
def add_student(self, id: str, name: str) -> None:
if id in self.students:
print(f"Student with ID {id} already exists.")
return
student = Student(id, name, {})
self.students[id] = student
def record_grade(self, id: str, course: str, grade: float) -> None:
if id not in self.students:
print(f"Student with ID {id} not found.")
return
s = self.students[id]
if course in s.grades:
print(f"Warning: about to overwrite grade for {s.name} in {course}.")
s.grades[course] = grade
def display_student(self, id: str) -> None:
if id not in self.students:
print(f"Student with ID {id} not found.")
return
s = self.students[id]
print(f"Student: {s.name} ({s.id})")
if len(s.grades) == 0:
print(f" (no grades yet)")
return
for course, grade in s.grades.items():
print(f" {course}: {grade}")
school = School({})
# Adding students
school.add_student("S001", "Alice")
school.add_student("S002", "Bob")
pprint(school)
# Recording grades
school.record_grade("S001", "Analyse", 5.0)
school.record_grade("S001", "ICC", 6.0)
school.record_grade("S002", "Analyse", 5.0)
school.record_grade("S002", "ICC", 5.5)
school.record_grade("S002", "ICC", 6.0)
pprint(school)
# # Displaying student information
school.display_student("S001")
school.display_student("S002")
Last modified: Monday, 27 May 2024, 17:01