Add basic programming/final task/grades.py
This commit is contained in:
163
basic programming/final task/grades.py
Normal file
163
basic programming/final task/grades.py
Normal file
@@ -0,0 +1,163 @@
|
||||
import csv
|
||||
|
||||
def readStudentFile(file_path):
|
||||
"""Reads student data from a file and returns a dictionary."""
|
||||
students = {}
|
||||
try:
|
||||
with open(file_path, 'r') as file:
|
||||
reader = csv.reader(file)
|
||||
for row in reader:
|
||||
student_id = row[0]
|
||||
first_name = row[1]
|
||||
last_name = row[2]
|
||||
courses = {row[i]: int(row[i + 1]) for i in range(3, len(row), 2)}
|
||||
students[student_id] = {
|
||||
'first_name': first_name,
|
||||
'last_name': last_name,
|
||||
'courses': courses
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"Error reading student file: {e}")
|
||||
return students
|
||||
|
||||
def saveStudentFile(file_path, students):
|
||||
"""Saves student data to a file."""
|
||||
try:
|
||||
with open(file_path, 'w', newline='') as file:
|
||||
writer = csv.writer(file)
|
||||
for student_id, data in students.items():
|
||||
row = [
|
||||
student_id,
|
||||
data['first_name'],
|
||||
data['last_name']
|
||||
]
|
||||
for course, grade in data['courses'].items():
|
||||
row.extend([course, grade])
|
||||
writer.writerow(row)
|
||||
except Exception as e:
|
||||
print(f"Error saving student file: {e}")
|
||||
|
||||
def menu():
|
||||
"""Displays the menu and gets the user's choice."""
|
||||
print("\nMenu:")
|
||||
print("1. Add new student")
|
||||
print("2. Update grade")
|
||||
print("3. Load grade updates from file")
|
||||
print("4. Generate student report")
|
||||
print("5. Generate course report")
|
||||
print("6. Exit")
|
||||
|
||||
while True:
|
||||
try:
|
||||
choice = int(input("Enter your choice: "))
|
||||
if 1 <= choice <= 6:
|
||||
return choice
|
||||
else:
|
||||
print("Invalid choice. Please choose between 1 and 6.")
|
||||
except ValueError:
|
||||
print("Invalid input. Please enter a number between 1 and 6.")
|
||||
|
||||
def add_new_student(students):
|
||||
"""Adds a new student to the data."""
|
||||
student_id = input("Enter student ID: ")
|
||||
if student_id in students:
|
||||
print("Error: Student with this ID already exists.")
|
||||
return
|
||||
|
||||
first_name = input("Enter first name: ")
|
||||
last_name = input("Enter last name: ")
|
||||
students[student_id] = {
|
||||
'first_name': first_name,
|
||||
'last_name': last_name,
|
||||
'courses': {}
|
||||
}
|
||||
print("Student added successfully.")
|
||||
|
||||
def updateGrade(students):
|
||||
"""Updates a grade for a student."""
|
||||
student_id = input("Enter student ID: ")
|
||||
if student_id not in students:
|
||||
print("Error: Student not found.")
|
||||
return
|
||||
|
||||
course = input("Enter course name: ").capitalize()
|
||||
try:
|
||||
grade = int(input("Enter grade (0-100): "))
|
||||
if 0 <= grade <= 100:
|
||||
students[student_id]['courses'][course] = grade
|
||||
print("Grade updated successfully.")
|
||||
else:
|
||||
print("Error: Grade must be between 0 and 100.")
|
||||
except ValueError:
|
||||
print("Error: Invalid grade format.")
|
||||
|
||||
def loadGrades(file_path, students):
|
||||
"""Loads grade updates from a file."""
|
||||
try:
|
||||
with open(file_path, 'r') as file:
|
||||
reader = csv.reader(file)
|
||||
for row in reader:
|
||||
student_id, course, grade = row
|
||||
if student_id in students:
|
||||
students[student_id]['courses'][course] = int(grade)
|
||||
else:
|
||||
print(f"Warning: Student ID {student_id} not found.")
|
||||
print("Grade updates loaded successfully.")
|
||||
except Exception as e:
|
||||
print(f"Error loading grades: {e}")
|
||||
|
||||
def generateStudentReport(students):
|
||||
"""Generates a report for a specific student."""
|
||||
student_id = input("Enter student ID: ")
|
||||
if student_id not in students:
|
||||
print("Error: Student not found.")
|
||||
return
|
||||
|
||||
student = students[student_id]
|
||||
print(f"\nReport for {student['first_name']} {student['last_name']}:")
|
||||
total, count = 0, 0
|
||||
for course, grade in student['courses'].items():
|
||||
print(f"{course}: {grade}")
|
||||
total += grade
|
||||
count += 1
|
||||
if count > 0:
|
||||
print(f"Average grade: {total / count:.2f}")
|
||||
|
||||
def generateCourseReport(students):
|
||||
"""Generates a report for a specific course."""
|
||||
course = input("Enter course name: ").capitalize()
|
||||
print(f"\nReport for course: {course}")
|
||||
total, count = 0, 0
|
||||
for student in students.values():
|
||||
if course in student['courses']:
|
||||
grade = student['courses'][course]
|
||||
print(f"{student['first_name']} {student['last_name']}: {grade}")
|
||||
total += grade
|
||||
count += 1
|
||||
if count > 0:
|
||||
print(f"Average grade: {total / count:.2f}")
|
||||
else:
|
||||
print("No students found for this course.")
|
||||
|
||||
def main():
|
||||
students = readStudentFile('students.csv')
|
||||
while True:
|
||||
choice = menu()
|
||||
if choice == 1:
|
||||
add_new_student(students)
|
||||
elif choice == 2:
|
||||
updateGrade(students)
|
||||
elif choice == 3:
|
||||
file_path = input("Enter grade updates file path: ")
|
||||
loadGrades(file_path, students)
|
||||
elif choice == 4:
|
||||
generateStudentReport(students)
|
||||
elif choice == 5:
|
||||
generateCourseReport(students)
|
||||
elif choice == 6:
|
||||
saveStudentFile('students.csv', students)
|
||||
print("Data saved. Exiting program.")
|
||||
break
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user