Create An Algorithm And Code For Processing Student Grades
Create an Algorithm and Code for Processing Student Grades from a File
For the following program: • Create an algorithm. • Code the program as grades.py. • Upload your algorithm and your program (grades.py).
Program Requirements:
- Read in the names and test grades of 5 students from the data file “grades.txt”. Use the split function to separate the names and test scores and convert the test scores to numeric values.
- Calculate the average of the test scores.
- Display the names, test scores, and the average on the screen in the specified format:
Name Grade
---------------------------
Mickey Mouse 90.0
Jane Doe 50.0
Minnie Mouse 95.0
Donald Duck 80.0
Daffy Duck 70.0
Average Grade: 77.0
Paper For Above instruction
Algorithm Design for Processing Student Grades
The program begins with defining an algorithm to process student grades stored in a text file, perform computations, display data, and update the file with new entries. The steps encompass file reading, parsing data, converting data types, computing averages, output formatting, and data appending.
Step 1: Initialization and File Reading
Initialize variables such as a list to store student data and a sum variable for total grades. Open the file "grades.txt" in read mode. Read all lines into a list. Close the file to ensure data integrity and free system resources.
Step 2: Data Processing and Parsing
Iterate over each line of the file. For each line, strip whitespace and split the line by spaces to separate the name(s) from the grade. Handle the case where names may include multiple words (e.g., "Mickey Mouse"). Extract the last token as the grade and the preceding tokens as the name. Convert the grade string to float for computation. Accumulate the grades to calculate the total sum for averaging. Store each student's name and grade in a structured format, like a list of dictionaries or tuples, for later display.
Step 3: Calculating the Average
Calculate the average grade by dividing the total sum of grades by the number of students, which is 5 in this context. Round the result to one decimal place for consistent formatting.
Step 4: Output Formatting and Display
Print headers "Name" and "Grade" and a separator line. Loop through the stored student data, format each name and grade with proper spacing, and print to the screen. Use string formatting to ensure grades are displayed with one digit after the decimal point. After listing all students, print the calculated average grade with the label "Average Grade".
Step 5: Prompting User for New Data
Ask the user to input a new student's first name, last name, and grade. Collect inputs with appropriate prompts. Convert the grade input to float. Concatenate first and last names to form the full name.
Step 6: Appending Data to the File
Open "grades.txt" in append mode. Write the new student's name and grade in the same format as existing records, ensuring consistency. Close the file to save changes.
Step 7: Error Handling & Validation (Optional)
Implement basic error handling such as input validation for the grade to be a number within a valid range (e.g., 0-100). Handle potential file errors gracefully, such as file not found or access issues.
Code Implementation: grades.py
grades.py
def main():
students = []
total_grades = 0.0
Read data from file
try:
with open("grades.txt", "r") as file:
lines = file.readlines()
except FileNotFoundError:
print("Error: 'grades.txt' file not found.")
return
Parse data and compute total to determine average
for line in lines:
line = line.strip()
if not line:
continue # skip empty lines
parts = line.split()
Last token is grade, preceding tokens are part of the name
*name_parts, grade_str = parts
name = " ".join(name_parts)
try:
grade = float(grade_str)
except ValueError:
print(f"Invalid grade value for {name}. Skipping.")
continue
students.append({'name': name, 'grade': grade})
total_grades += grade
Calculate average grade
num_students = len(students)
if num_students == 0:
print("No student data available.")
return
average_grade = round(total_grades / num_students, 1)
Display header
print(f"{'Name':10}")
print("-" * 30)
for student in students:
print(f"{student['name']:10.1f}")
print(f"\nAverage Grade: {average_grade:.1f}\n")
Prompt user for new student data
first_name = input("Enter the first name of the new student: ").strip()
last_name = input("Enter the last name of the new student: ").strip()
while True:
grade_input = input("Enter the grade of the new student: ").strip()
try:
new_grade = float(grade_input)
if 0
break
else:
print("Please enter a grade between 0 and 100.")
except ValueError:
print("Invalid input. Please enter a numeric grade.")
new_name = f"{first_name} {last_name}"
Append new data to the file
try:
with open("grades.txt", "a") as file:
file.write(f"{new_name} {new_grade}\n")
except IOError:
print("Error: Could not write to 'grades.txt'.")
if __name__ == "__main__":
main()
References
- Python Software Foundation. (2023). Official Python documentation. https://docs.python.org/3/
- Gaddis, T. (2020). Starting Out with Python: From Control Structures through Data Structures. Pearson.
- Johnson, J. (2019). Python Programming for Beginners. Wiley.
- Downey, A. (2015). Think Python: How to Think Like a Computer Scientist. Green Tea Press.
- Beazley, D. (2013). Python Essential Reference. Pearson.
- McDonald, D. (2011). Python in Easy Steps. In Easy Steps Limited.
- Van Rossum, G., & Drake, F. L. (2009). Python reference manual. CWI (Centrum Wiskunde & Informatica).
- Al Sweigart. (2015). Automate the Boring Stuff with Python. No Starch Press.
- Hassan, H. (2018). Data Analysis with Python. Packt Publishing.
- Chung, J. (2020). Learning Python for Data Analysis and Visualization. Packt Publishing.