Skip to main content
3 of 3
added 22 characters in body; edited title
200_success
  • 144.2k
  • 22
  • 188
  • 473

Program to compute final grade for weighted assignments

I wrote a "gradebook" program. This takes in grades for various assignments. The assignments types are weighted differently and final grade is computed at the end. The code works but I can't help but think I am being ham handed in my approach. Should I be using a dictionary instead of storing things like hw_final, lab_final, and exam_final as global variables?

hw_tally = 0
hw_weight_count = 0
hw_final = 0
lab_tally = 0
lab_weight_count = 0
lab_final = 0
exam_tally = 0
exam_weight_count = 0
exam_final = 0


def assignment(kind, grade, weight=1):
    global hw_tally, hw_weight_count, hw_final, lab_tally, lab_weight_count, lab_final, exam_tally, exam_weight_count, exam_final
    if kind == 'hw':
        hw_weight_count += weight
        hw_temporary = (grade * weight)     
        hw_tally += hw_temporary
        hw_final = hw_tally/hw_weight_count
    elif kind == 'lab':
        lab_weight_count += weight
        lab_temporary = (grade * weight)     
        lab_tally += lab_temporary
        lab_final = lab_tally/lab_weight_count
    elif kind == 'exam':
        exam_weight_count += weight
        exam_temporary = (grade * weight)   
        exam_tally += exam_temporary
        exam_final = exam_tally/exam_weight_count


assignment('hw', 81)
assignment('exam', 90, 4)
assignment('hw', 100, 2)
assignment('lab', 84, 3)
assignment('lab', 90, 2)
assignment('exam', 78)
assignment('exam', 85)
assignment('lab', 88)
assignment('exam', 75)

hw_weight_percent = 0.4
lab_weight_percent = 0.1
exam_weight_percent = 0.5

final_grade = ((hw_final * hw_weight_percent) + (lab_final * 
lab_weight_percent) + (exam_final * exam_weight_percent))
print ("Final grade = ", final_grade)