Applying the Grading System to a Real Dataset
Now, let us apply our grading system to a more realistic scenario. We will create a program that reads student data from a file, calculates grades, and writes a comprehensive report.
Creating a Sample Dataset
First, let us create a file with sample student data. Create a new file called student_data.csv
in the /home/labex/project
directory with the following content:
name,subject,marks
John,Mathematics,88
Emily,Mathematics,92
Michael,Mathematics,75
Sophia,Mathematics,68
Daniel,Mathematics,42
Olivia,Mathematics,95
William,Mathematics,73
Emma,Mathematics,60
James,Mathematics,79
Ava,Mathematics,85
Creating the Complete Grading Application
Now, create a new file called grading_application.py
in the /home/labex/project
directory:
def get_grade_with_feedback(marks):
"""
Convert numerical marks to letter grades with personalized feedback.
Returns a tuple containing the grade and a feedback message.
"""
try:
marks = float(marks)
if marks < 0 or marks > 100:
return (None, "Invalid marks: must be between 0 and 100")
elif marks >= 90:
return ('A', "Excellent! Outstanding performance.")
elif marks >= 80:
return ('B', "Very good! Above average performance.")
elif marks >= 70:
return ('C', "Good work! Average performance.")
elif marks >= 60:
return ('D', "Satisfactory. Below average but passing.")
else:
return ('F', "Needs improvement. Please study more.")
except ValueError:
return (None, "Invalid marks: not a number")
def process_student_data(input_filename, output_filename):
"""
Process student data from a CSV file and generate a report.
"""
try:
## Read the input file
with open(input_filename, 'r') as file:
lines = file.readlines()
## Skip the header line
headers = lines[0].strip().split(',')
data = [line.strip().split(',') for line in lines[1:]]
## Prepare the output
output_lines = ["Student Grade Report\n", "=" * 20 + "\n\n"]
## Calculate statistics
valid_marks = []
grade_counts = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0, 'Invalid': 0}
## Process each student
for student in data:
name, subject, marks = student
grade, feedback = get_grade_with_feedback(marks)
if grade:
valid_marks.append(float(marks))
grade_counts[grade] += 1
output_lines.append(f"Student: {name}\n")
output_lines.append(f"Subject: {subject}\n")
output_lines.append(f"Marks: {marks}\n")
output_lines.append(f"Grade: {grade}\n")
output_lines.append(f"Feedback: {feedback}\n\n")
else:
grade_counts['Invalid'] += 1
output_lines.append(f"Student: {name}\n")
output_lines.append(f"Subject: {subject}\n")
output_lines.append(f"Error: {feedback}\n\n")
## Calculate statistics
if valid_marks:
average_mark = sum(valid_marks) / len(valid_marks)
max_mark = max(valid_marks)
min_mark = min(valid_marks)
output_lines.append("Class Statistics\n")
output_lines.append("-" * 15 + "\n")
output_lines.append(f"Average Mark: {average_mark:.2f}\n")
output_lines.append(f"Highest Mark: {max_mark:.1f}\n")
output_lines.append(f"Lowest Mark: {min_mark:.1f}\n\n")
output_lines.append("Grade Distribution\n")
output_lines.append("-" * 17 + "\n")
for grade, count in grade_counts.items():
output_lines.append(f"{grade}: {count}\n")
## Write the output file
with open(output_filename, 'w') as file:
file.writelines(output_lines)
print(f"Report successfully generated and saved to {output_filename}")
except Exception as e:
print(f"An error occurred: {str(e)}")
## Run the application
input_file = "/home/labex/project/student_data.csv"
output_file = "/home/labex/project/grade_report.txt"
process_student_data(input_file, output_file)
## Display the report in the console as well
print("\nGenerated Report Contents:")
print("--------------------------")
with open(output_file, 'r') as file:
print(file.read())
Running the Complete Application
Run the application:
python3 /home/labex/project/grading_application.py
The program will read the student data, calculate grades, generate a report, and display it in the console. You should see output similar to:
Report successfully generated and saved to /home/labex/project/grade_report.txt
Generated Report Contents:
--------------------------
Student Grade Report
====================
Student: John
Subject: Mathematics
Marks: 88
Grade: B
Feedback: Very good! Above average performance.
Student: Emily
Subject: Mathematics
Marks: 92
Grade: A
Feedback: Excellent! Outstanding performance.
...
Class Statistics
---------------
Average Mark: 75.70
Highest Mark: 95.0
Lowest Mark: 42.0
Grade Distribution
-----------------
A: 2
B: 2
C: 3
D: 1
F: 2
Invalid: 0
Examining the Report File
You can also check the generated report file:
cat /home/labex/project/grade_report.txt
The file should contain the same content that was displayed in the console.
Understanding the Complete Application
The complete grading application we created demonstrates several important programming concepts:
- File I/O: Reading data from and writing data to files
- Data Processing: Converting and analyzing raw data
- Statistics Calculation: Computing averages and finding minimum/maximum values
- Error Handling: Managing potential errors during file operations
- Formatting Output: Creating a well-structured, readable report
This application represents a real-world use case for our grading system, showing how Python's if-elif-else statements can be applied to solve practical problems in educational settings.