Question:
The student data and teacher data doesn’t save therefore my printing breaks, I want to be able to save the data in the __init__
function rather than doing it after I create the object. I have tried to use AI but it isn’t working.
Repl link:
https://replit.com/@SalladShooter/Student-Database#main.py
main.py
from Student import *
import random
# List of first names and last names
first_names = ['John', 'Jane', 'Michael', 'Emily', 'David', 'Sarah']
last_names = ['Smith', 'Johnson', 'Brown', 'Wilson', 'Davis', 'Taylor']
# Generate random names
def generate_random_name():
first_name = random.choice(first_names)
last_name = random.choice(last_names)
return first_name, last_name
# Generate random teachers and grades
def generate_random_data():
teachers = ['Mr. Johnson', 'Ms. Smith', 'Mr. Davis', 'Ms. Brown', 'Mr. Wilson']
grades = [random.randint(70, 100) for _ in range(len(teachers))]
return {teacher: f"{grade}%" for teacher, grade in zip(teachers, grades)}
# Generate and save random students
for _ in range(10):
first_name, last_name = generate_random_name()
student_data = generate_random_data()
student = Student(last_name, first_name, student_data)
print(student)
student.print_class()
Student.py
import json
class Student:
"""
Represents a student with a last name, first name, and a list of teachers and grades.
"""
def __init__(self, lastName, firstName, teachers_grades: dict):
self.lastName = lastName
self.firstName = firstName
self.teachers_grades = self._convert_grades(teachers_grades)
self.save_json() # Automatically save data when a student is created
def _convert_grades(self, grades):
converted_grades = {}
for teacher, grade in grades.items():
converted_grades[teacher] = float(grade.strip('%'))
return converted_grades
def save_json(self):
student_database = {
f"{self.lastName}, {self.firstName}": self.teachers_grades
}
with open('student-database.json', 'w') as json_file:
json.dump(student_database, json_file, indent=4)
def __str__(self):
formatted_grades = "\n".join(f"\t| {teacher}: {grade}%" for teacher, grade in self.teachers_grades.items())
return f"""
{self.lastName}, {self.firstName}
{formatted_grades}
"""
def print_class(self, teacher_name=None):
try:
with open('student-database.json', 'r') as json_file:
student_database = json.load(json_file)
except Exception as e:
print(f"An error occurred while reading the file: {e}")
student_database = {}
if teacher_name:
if teacher_name in student_database:
print(f"\nClass: {teacher_name}\n")
for student, grade in student_database[teacher_name].items():
print(f"\t| {student} | {grade}")
else:
print(f"No class found for teacher: {teacher_name}")
else:
for teacher, students in student_database.items():
print(f"\nClass: {teacher}\n")
for student, grade in students.items():
print(f"\t| {student} | {grade}")
def print_students(self):
print(f"{self.lastName}, {self.firstName}:")
for teacher, grade in self.teachers_grades.items():
print(f"\t| {teacher} | {grade}%")