1

This program should display:

Here are your grades
Math score is 100
Science score is 90
Reading score is 70

Average grade score is 86.66

However with the code I have, it is displaying this:

Here are your grades:
Math score is 100.0
Sciencee score is 95.0
Reading score is 86.66666666666667
The average score is 86.66666666666667

So basically the average is correct but now the scores are not.

gradesFile = open("grades.txt","r")

#Establishes the variables
total = 0
numberOfLines = 0
lines = 0
print('Here are your grades:','\n')

# Creates a loop that will print out each score, until there aren't anymore
# scores to read. For example:
#Math score is 100
#Science score is 90
#and so on.
for line in gradesFile:
   numberOfLines += 1
   lines = line.strip()
   total += float(gradesFile.readline())
   score = total / numberOfLines
   print(lines + ' score is', score)

gradesFile.close
average = float(total) / (numberOfLines)
print('The average score is', average)

The grades.txt file looks like this:

Math

100.0

Science

90.0

Reading

70.0

sparx
  • 51
  • 4

1 Answers1

0

Your score is essentially a rolling average. There's no need for that, just print it directly:

for line in gradesFile:
   numberOfLines += 1

   lines = line.strip()

   score =  float(gradesFile.readline())

   total += score

   print(lines + ' score is', score)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • @sparx and then divide `total` with `numberOfLines` to get the `average`. – UdonN00dle Jun 30 '19 at 20:03
  • Adding on: if you'd like only a couple of the numbers to be displayed after the decimal point, you can look into string formatting [here](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points). – ladygremlin Jun 30 '19 at 21:39