This code is part of a larger code that generates an Arithmetic Quiz, although the code I have show below just saves the score that the user got on the test and their name. When saving the code it checks if the user has taken the quiz before. If the user has taken the quiz before it saves it as 'Older Score' or 'Oldest Score', however if the user has not taken the quiz before it generates a new row for them. Additionally it works out the average score and highest score for all users it has the data for. For my task I'm supposed to make the code as short as possible.
name = ""+first_name+" "+last_name
rows_data = []
class_file_names = ['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
scan = open(class_file_names[int(math_class)-1], 'r+')
rows = csv.reader(scan)
for row in rows:
rows_data.append(row)
scan.close()
class_file_names=['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
csvfile=open(class_file_names[int(math_class)-1], 'w', newline="")
fieldnames = ['Student Name', 'Oldest Score', 'Older Score', 'Latest Score', 'Average', 'Highest']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
nameFound=False
for x in rows_data[1:]:
if x[0] == name:
x[3]=x[2]
x[2]=x[1]
x[1]=str(score)
x[4]=(int(x[1])+int(x[2])+int(x[3]))/3
x[5]=max(x[1],x[2],x[3])
nameFound=True
writer.writerow({'Student Name': x[0], 'Oldest Score': x[3], 'Older Score': x[2], 'Latest Score': x[1], 'Average': x[4], 'Highest' : x[5]})
if nameFound==False:
writer.writerow({'Student Name': name, 'Latest Score': score, 'Older Score': '0', 'Oldest Score': '0', 'Average': score, 'Highest': score})
csvfile.close()
input("Test complete! Press anything to close.")