0

I'm a Python beginner and I can't get one thing working. See, our teacher told us to make a function to calculate average score of all exam scores, with undefined number of exams. It has to be in Python 2.7.

def main():
    print("This program computes the average of multiple exam scores.")

scoresno = input("Enter number of exam scores: ")
for scores in range(scoresno):
    scores = input("Enter exam score: ")

average = scores/(scoresno + 0.0)

print "Exam score average is:", (average)
main()

that obviously doesn't work, how can I get it to work?

MSmS
  • 189
  • 1
  • 4
  • 15

3 Answers3

1

Inside of your first for loop you are overwriting the variable scores on each iteration. Instead you should create a variable to keep track of the combined score before the loop and then on each iteration add the current score. For example:

total = 0.0
for scores in range(scoresno):
     score = input("Enter exam score: ")
     total += score
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

You could sum the scores directly, as you loop:

total = 0.0
for i in range(scoresno):
    total += input("Enter exam score: ")

average = total/scoresno

The alternative is to use a list and append each new value to it, then sum the lot:

scores = []
for i in range(scoresno):
    score = input("Enter exam score: ")
    scores.append(score)

total = sum(scores)
average = total/float(scoresno)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

First, beware of your indentation! Python has a strict rule on code indendation.

Second, why taking a step by step average? A better practice is take all the inputs at once and then divide by the amount of inputs.

Here's your code corrected:

def main():
    print("This program computes the average of multiple exam scores.")
    scoresno = input("Enter number of exam scores: ")
    scoreslist = list() #Create a list of scores to be stored for evaluation
    for scores in range(scoresno):
        scoreslist.append(input("Enter exam score: ")) #Get the score and immediately store on the list
    average = float(sum(scoreslist)) / len(scoreslist)
    print "Exam score average is:", (average)

if __name__=='__main__': #Run this code only if this script is the main one
    main()

sum(iterable) sums all the elements of the array of numbers and returns the result. Wonder why the cast to float? If we don't cast it, we may have division of integers yielding a integer result (I guess you want results like 7.25), so if either one of the numbers should be a float (see here for more info).

Community
  • 1
  • 1
SonicARG
  • 499
  • 9
  • 14