Danny Garcia
Danny Garcia

Reputation: 227

Averaging different iterations of a variable in a for loop

I can't seem to figure this out - I want to get the average of all the inputs at the end of this program but I don't know how to save the inputs with each iteration of the loop. Any help would be much appreciated, thanks!

students = int(input("How many students are in your class?"))

while students <= 0:
    print ("Invalid # of students. Try again.")
    students = int(input("How many students are in your class?"))

studentnum = 1 

for x in range (0, students):
    print ("*** Student", studentnum, " ***")
    score1 = int(input("Enter score for test #1"))
    while score1 < 0:
            print ("Invalid score. Try again.")
            score1 = int(input("Enter score for test #1"))
    score2 = int(input("Enter score for test #2"))
    while score1 < 0:
            print ("Invalid score. Try again.")
            score1 = int(input("Enter score for test #1"))
    part1 = score1 + score2
    av = part1 / 2
    print ("Average score for student #", studentnum, "is", av)
    studentnum = studentnum + 1

# figure out how to average out all student inputs

Upvotes: 1

Views: 65

Answers (2)

emmagordon
emmagordon

Reputation: 1222

You can build up a list of average scores for each student (by appending to it on each loop iteration), and then find the average of those after exiting the loop:

student_average_scores = []

for student in xrange(students):
    # <your code that gets av>
    student_average_scores.append(av)

average_score = sum(student_average_scores) / float(len(student_average_scores))

Upvotes: 1

Brendan Abel
Brendan Abel

Reputation: 37549

Just create something to store them in outside your loop

scores = []
for x in range (0, students):
   ...
   scores.append({'score1': score1, 'score2': score2, 'avg', av})

total_avg = sum(d['avg'] for d in scores) / len(scores)

Upvotes: 2

Related Questions