Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
14 kB
1
Indexable
Never
import os

class GradeSystem:
    FILE_NAME = 'GSM.txt'
    MENU_OPTIONS = [
        "1) Add grade",
        "2) Update grade",
        "3) Delete grade",
        "4) Show all grades",
        "5) Calculate average",
        "6) Find and list",
        "0) Exit"
    ]

    @staticmethod
    def print_menu():
        print("╔" + "═" * 29 + "╗")
        print("║" + " " * 10 + "☆ MENU ☆" + " " * 11 + "║")
        print("╠" + "═" * 29 + "╣")
        for option in GradeSystem.MENU_OPTIONS:
            print(f"║ {' ' * 2}{option}{' ' * (29 - len(option) - 3)}║")
        print("╚" + "═" * 29 + "╝")

    @staticmethod
    def is_valid_student_ID(student_ID):
        return len(student_ID) == 8 

    @staticmethod
    def is_valid_score(score):
        try:
            score = str(score)
            return 0 <= float(score) <= 10
        except ValueError:
            return False

    @staticmethod
    def calculate_final_result(ws, pt, ass, pe, fe):
        return 0.1 * (ws + pt + ass) + 0.4 * pe + 0.3 * fe

    @staticmethod
    def get_status(fr, ws, pt, ass, fe):
        return 'Pass' if all([ws > 0, pt > 0, ass > 0, fe >= 4, fr >= 5]) else 'Failed'

    @staticmethod
    def input_score(prompt):
        score = input(prompt)
        while not GradeSystem.is_valid_score(score):
            score = input("Invalid score. Must be between 0 and 10. Please re-enter: ")
        return float(score)

    def id_exists(self, student_ID):
        with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
            for line in file:
                if line.startswith(student_ID):
                    return True
        return False

    def add_grade(self):
        choice = input("Add (1) Class (2) Student: \nYour choice: ").strip()

        if choice == "1":
            name_class = input("Class name: ").strip()
            with open(GradeSystem.FILE_NAME, 'a', encoding='utf-8') as file:
                file.writelines(f"Class: {name_class}\n\n")
                
            print("Class has been added successfully.")

        elif choice == "2":
            student_ID = input("Student ID: ").strip()
            while not GradeSystem.is_valid_student_ID(student_ID) or self.id_exists(student_ID):
                student_ID = input("Invalid or duplicate Student ID. Must be 8 digits and unique. Please re-enter: ").strip()

            student_name = input("Student Name: ").strip()
            ws = GradeSystem.input_score("Workshop: ")
            pt = GradeSystem.input_score("Progress Test: ")
            ass = GradeSystem.input_score("Assignment: ")
            pe = GradeSystem.input_score("Practical Exam: ")
            fe = GradeSystem.input_score("Final Exam: ")

            fr = GradeSystem.calculate_final_result(ws, pt, ass, pe, fe)
            status = GradeSystem.get_status(fr, ws, pt, ass, fe)

            class_name = input("Class name: ").strip()
            with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
                lines = file.readlines()
            
            new_lines = []
            class_found = False

            for line in lines:
                new_lines.append(line)
                if line.strip() == f"Class: {class_name}":
                    class_found = True
                    new_lines.append(f"{student_ID} {student_name} {ws} {pt} {ass} {pe} {fe} {fr:.2f} {status}\n")
            if not class_found:
                print("Invalid Class, try again.")
            else:
                print("---Finish Adding---")
                with open(GradeSystem.FILE_NAME, 'w', encoding='utf-8') as file:
                    file.writelines(new_lines)

    def update_grade(self):
        student_ID = input("Student ID: ").strip()
        while not GradeSystem.is_valid_student_ID(student_ID) or not self.id_exists(student_ID):
            student_ID = input("Invalid or non-existent Student ID. Must be 8 digits and already in the system. Please re-enter: ").strip()

        student_name = input("Student Name: ").strip()
        ws = GradeSystem.input_score("Workshop: ")
        pt = GradeSystem.input_score("Progress Test: ")
        ass = GradeSystem.input_score("Assignment: ")
        pe = GradeSystem.input_score("Practical Exam: ")
        fe = GradeSystem.input_score("Final Exam: ")

        fr = GradeSystem.calculate_final_result(ws, pt, ass, pe, fe)
        status = GradeSystem.get_status(fr, ws, pt, ass, fe)

        updated = False
        with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
            lines = file.readlines()

        with open(GradeSystem.FILE_NAME, 'w', encoding='utf-8') as file:
            for line in lines:
                if line.startswith(f"{student_ID}"):
                    file.write(f"{student_ID} {student_name} {ws} {pt} {ass} {pe} {fe} {fr:.2f} {status}\n")
                    updated = True
                else:
                    file.write(line)

        if updated:
            print("Grade has been updated successfully.")
        else:
            print("Student not found.")

    def delete_grade(self):
        choice = input("Delete: (one) or (all)\nYour choice: ").strip().lower()

        if choice == "one" or choice == "1":
            student_ID = input("Student ID: ").strip()

            with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
                lines = file.readlines()

            with open(GradeSystem.FILE_NAME, 'w', encoding='utf-8') as file:
                for line in lines:
                    if not line.startswith(f"{student_ID}"):
                        file.write(line)

            print("Grade has been deleted.")
        elif choice == "all":
            open(GradeSystem.FILE_NAME, 'w', encoding='utf-8').close()
            print("All grades have been deleted.")

    def show_all_grades(self):
        print("Grade List:")
        print("=" * 24)
        with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
            content = file.read().strip()
            if content:
                print(content)
            else:
                print("No data available.")
        print("=" * 24)

    def calculate_average(self):
        choice = input("Enter your choice, average Class(1) or Student(2): ").strip()

        if choice == "1":
            class_name = input("Enter the class name: ").strip()
            totals = {'ws': 0, 'pt': 0, 'ass': 0, 'pe': 0, 'fe': 0, 'count': 0}
            class_found = False

            with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
                lines = file.readlines()

            for i, line in enumerate(lines):
                if line.strip() == f"Class: {class_name}":
                    class_found = True
                    j = i + 1
                    while j < len(lines) and not lines[j].startswith("Class:"):
                        parts = lines[j].strip().split()
                        if len(parts) >= 8:
                            totals['ws'] += float(parts[2])
                            totals['pt'] += float(parts[3])
                            totals['ass'] += float(parts[4])
                            totals['pe'] += float(parts[5])
                            totals['fe'] += float(parts[6])
                            totals['count'] += 1
                        j += 1
                    break

            if class_found:
                if totals['count'] > 0:
                    print(f"Average Workshop for {class_name}: {totals['ws'] / totals['count']:.2f}")
                    print(f"Average Progress Test for {class_name}: {totals['pt'] / totals['count']:.2f}")
                    print(f"Average Assignment for {class_name}: {totals['ass'] / totals['count']:.2f}")
                    print(f"Average Practical Exam for {class_name}: {totals['pe'] / totals['count']:.2f}")
                    print(f"Average Final Exam for {class_name}: {totals['fe'] / totals['count']:.2f}")
                else:
                    print("No data available to calculate averages for this class.")
            else:
                print("Class not found.")

        elif choice == "2":
            student_ID = input("Student ID: ").strip()
            student_found = False

            with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
                for line in file:
                    if line.startswith(f"{student_ID}"):
                        parts = line.strip().split()
                        if len(parts) >= 8:
                            scores = [float(parts[i]) for i in range(2, 7)]
                            avg = sum(scores) / 5
                            print(f"Average grade for {student_ID}: {avg:.2f}")
                            student_found = True
                            break
            
            if not student_found:
                print("Student data not found.")

    @staticmethod
    def print_table_student(header, rows):
        row_format = "|{:<12}|{:<14}|{:<14}|{:<16}|{:<14}|{:<15}|{:<12}|{:<12}|{:<10}|"
        print(row_format.format(*header))
        print("=" * 90)
        for row in rows:
            print(row_format.format(*row))

    @staticmethod
    def print_table_class(header, rows):
        row_format = "|{:<12}|{:<14}|{:<14}|{:<16}|{:<14}|{:<12}|"
        print(row_format.format(*header))
        print("=" * 90)
        for row in rows:
            print(row_format.format(*row))

    def find_and_list_student_class(self):
        choice = input("Find and list Student (1) or Class (2)\nYour choice: ").strip()
        if choice == '1':
            search_ID = input("Enter Student ID (leave blank to skip): ").strip()
            with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
                student_info = []
                for line in file:
                    parts = line.strip().split()
                    if parts and parts[0] == search_ID: 
                        student_info.append(parts)
                        break
                if student_info:
                    header = ["Student ID", "Student Name", "Workshop", "Progress Test", "Assignment", "Practical Exam", "Final Exam", "Final Result", "Status"]
                    GradeSystem.print_table_student(header, student_info)
                else:
                    print("Student not found.")
                    
        elif choice == '2':
            class_name = input("Class name: ").strip()
            with open(GradeSystem.FILE_NAME, 'r', encoding='utf-8') as file:
                lines = file.readlines()
            
            info_class = []
            collecting = False
            for line in lines:
                if line.startswith("Class:"):
                    parts = line.strip().split()
                    if parts[1] == class_name:
                        collecting = True
                    else:
                        collecting = False
                elif collecting and line.strip():
                    info_class.append(line.strip().split())
            
            if info_class:
                workshop_total = 0
                progress_test_total = 0
                practical_exam_total = 0
                final_exam_total = 0
                count = len(info_class)
                
                for row in info_class:
                    workshop_total += float(row[2])
                    progress_test_total += float(row[3])
                    practical_exam_total += float(row[4])
                    final_exam_total += float(row[5])
                
                workshop_avg = workshop_total / count
                progress_test_avg = progress_test_total / count
                practical_exam_avg = practical_exam_total / count
                final_exam_avg = final_exam_total / count
                
                status = "Pass" if all(avg >= 5 for avg in [workshop_avg, progress_test_avg, practical_exam_avg, final_exam_avg]) else "Failed"
                
                info_class = [[class_name, f"{workshop_avg:.2f}", f"{progress_test_avg:.2f}", f"{practical_exam_avg:.2f}", f"{final_exam_avg:.2f}", status]]
                header = ["Class name", "Workshop", "Progress Test", "Practical Exam", "Final Exam", "Status"]
                GradeSystem.print_table_class(header, info_class)
            else:
                print("Class not found.")
                



    def main(self):
        functions = [
            self.add_grade,
            self.update_grade,
            self.delete_grade,
            self.show_all_grades,
            self.calculate_average,
            self.find_and_list_student_class
        ]

        while True:
            os.system('cls')
            GradeSystem.print_menu()
            try:
                choice = int(input("Enter your choice: ").strip())
                if choice == 0:
                    break
                elif 1 <= choice <= 6:
                    functions[choice - 1]()
                    input("\nPress Enter to return to the main menu.")
                else:
                    print("Invalid choice. Please try again.")
            except ValueError:
                print("Invalid input. Please enter a number.")
            except Exception as e:
                print(f"An error occurred: {e}")

        print("Program terminated.")

if __name__ == "__main__":
    GradeSystem().main()
Leave a Comment