Search code examples
pythonfunctionaverage

How to make my program add the two averages together and calculate one average for the "class"?


I am trying to get my program to add all averages together to generate one big "class" average. The code is only taking the last individual average and dividing that by the number of students in calc_average. Any ideas? Here's my code:

def calc_average(total):
    return total / student_num
   

def determine_score(grade):
    if 90 <= grade <=100:
        return 'A'
    elif 80 <= grade <= 89:
        return 'B'
    elif 70 <= grade <= 79:
        return 'C'
    elif 60 <= grade <= 69:
        return 'D'
    else:
        return 'F'


student_num=int(input('How many students?'))
for j in range(student_num):
    scores = []
    sum=0
    total=0
    for i in range(0,5):
        score = int(input('Enter Test Scores'))
        print ('Your letter grade is: ', determine_score(score))
        scores.append(score)
        sum=sum+score
    iavg=sum/5
    print('Your average is:', iavg)
total=total+iavg
    
cavg=calc_average(total)
abc_grade=determine_score(cavg)

print('Class average is: ' + str(cavg))
print("The class letter grade would be: " + str(abc_grade))

OUTPUT: How many students?2

Enter Test Scores80

Your letter grade is: B

Enter Test Scores80

Your letter grade is: B

Enter Test Scores80

Your letter grade is: B

Enter Test Scores80

Your letter grade is: B

Enter Test Scores80

Your letter grade is: B

Your average is: 80.0

Enter Test Scores90

Your letter grade is: A

Enter Test Scores90

Your letter grade is: A

Enter Test Scores90

Your letter grade is: A

Enter Test Scores90

Your letter grade is: A

Enter Test Scores90

Your letter grade is: A

Your average is: 90.0

Class average is: 45.0

The class letter grade would be: F


Solution

  • There are a couple things you can fix.

    1. Total is being set to 0 every time you loop for a new student. Put it above the loop.
    2. You are adding to total after both loops have already gone. Put the addition to total in the loop itself.

    These will get your program to run as intended. However, there are still things you can do to make this closer to best practices.

    1. Include a space in your inputs, something like "Input Test Score: "
    2. You're passing total to an average function, but treating num_students as a global value. While this doesn't break anything, it doesn't look right.