-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment06
More file actions
129 lines (110 loc) · 4.62 KB
/
Assignment06
File metadata and controls
129 lines (110 loc) · 4.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# ------------------------------------------------------------------------------------------ #
# Title: Assignment06
# Desc: This assignment demonstrates using functions with structured error handling
# Change Log: (Who, When, What)
# RRoot,1/1/2030,Created Script
# Julianne Tillmann, 11/18/2024, Added functions and error handling.
# ------------------------------------------------------------------------------------------ #
import json # Enables work with JSON files
# Define the Data Constants
MENU: str = '''
---- Course Registration Program ----
Select from the following menu:
1. Register a Student for a Course
2. Show current data
3. Save data to a file
4. Exit the program
-----------------------------------------
'''
FILE_NAME: str = "Enrollments.json"
students: list = [] # A table of student data
# Class Definitions
class FileProcessor:
"""Handles file read/write operations"""
@staticmethod
def read_data_from_file(file_name: str, student_data: list) -> None:
"""Reads data from a file into a list of dictionaries"""
try:
with open(file_name, "r") as file:
student_data.extend(json.load(file))
print(f"Data loaded successfully from {file_name}.")
except FileNotFoundError:
print(f"{file_name} was not found. A new file will be created.")
except json.JSONDecodeError:
print(f"Error decoding JSON data in {file_name}.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
@staticmethod
def write_data_to_file(file_name: str, student_data: list) -> None:
"""Writes data from a list of dictionaries to a file"""
try:
with open(file_name, "w") as file:
json.dump(student_data, file)
print(f"Data saved successfully to {file_name}.")
except Exception as e:
print(f"An unexpected error occurred while saving data: {e}")
class IO:
"""Handles input and output operations"""
@staticmethod
def output_menu(menu: str) -> None:
"""Displays a menu of choices to the user"""
print(menu)
@staticmethod
def input_menu_choice() -> str:
"""Gets the user's menu choice"""
return input("What would you like to do? ")
@staticmethod
def input_student_data(student_data: list) -> None:
"""Gets student data from the user and adds it to the list"""
try:
student_first_name = input("Enter the student's first name: ")
if not student_first_name.isalpha():
raise ValueError("First name must only contain letters.")
student_last_name = input("Enter the student's last name: ")
if not student_last_name.isalpha():
raise ValueError("Last name must only contain letters.")
course_name = input("Enter the course name: ")
# Create a new dictionary and append it to the list
new_student = {
"FirstName": student_first_name,
"LastName": student_last_name,
"CourseName": course_name
}
student_data.append(new_student)
print(f"Student {student_first_name} {student_last_name} registered for {course_name}.")
except ValueError as e:
print(f"Input error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
@staticmethod
def output_student_courses(student_data: list) -> None:
"""Displays all students and their courses"""
print("\nCurrent Enrollments:")
if student_data:
for student in student_data:
try:
print(f"{student['FirstName']} {student['LastName']} - {student['CourseName']}")
except KeyError as e:
print(f"Error: Missing {e} in student record {student}")
else:
print("No data available.")
# Main Body
if __name__ == "__main__":
# Load existing data from the file
FileProcessor.read_data_from_file(FILE_NAME, students)
while True:
# Display menu and get user choice
IO.output_menu(MENU)
choice = IO.input_menu_choice()
# Process user choice
if choice == "1":
IO.input_student_data(students)
elif choice == "2":
IO.output_student_courses(students)
elif choice == "3":
FileProcessor.write_data_to_file(FILE_NAME, students)
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")