-1

I need to find the average of 5 assignments = two inputs. I'm getting a result, but its no correct. Here is what I have:

def main():

  # list of grades
   x = []

   # count of students 
   n = 5

   # fill list with grades from console input
   # using pythonic generator
   x = [int(input('Please enter the grade you got on assignment {}: '.format(i+1))) for i in range(n)]

   midTermGrade = int(input('Please enter the grade you got on you Mid-Term: '))
   finalGrade = int(input('Please enter the grade you got on you Final: '))

   average_assignment_grade = sum(x) + midTermGrade + finalGrade / 7 

   print('Avg grade is ', average_assignment_grade)

main()

As you can see here, the math is wrong, the average suppose to be around 28, not 114

Python Console

David
  • 1,987
  • 5
  • 33
  • 65
  • 2
    You have to enclose the whole expression of addition with parentheses. Operator precedence and PEMDAS, ie `(sum(x) + midTermGrade + finalGrade) / 7` – Andrew Li Aug 27 '16 at 00:00

2 Answers2

2

There is a problem with order of operations. You need to change:

average_assignment_grade = sum(x) + midTermGrade + finalGrade / 7 

to:

average_assignment_grade = (sum(x) + midTermGrade + finalGrade) / 7 

You can read about Python operator precedence here.

Karin
  • 8,404
  • 25
  • 34
0

Karin's answer is correct. Python uses BEDMAS, and that is why you didn't get the expected result.


However you're using Python 3. The statistics module was added in Python 3.4; it has the mean function that will calculate the mean (or "average"):

from statistics import mean

average_assignment_grade = mean(x + [midTermGrade, finalGrade])

The rationale behind this function is that it is not prone to many rounding errors:

>>> a = 100000000000000000.0
>>> sum([a, 3.0, -a) / 3
0.0

but

>>> statistics.mean([a, 3.0, -a])
1.0