Question

im new Python and I am practicing a few things but I couldnt seem to work out why the 4 grades shown below in my code wont properly divide by 4. E.g I will type all the grades as 2 and be shown 6.5 as the total grade average.

Heres the code:

#FinalGrade
Student = str(input("Student Name: "))
Grade1 = int(input("Enter Student's First Grade: "))
Grade2 = int(input("Enter Student's Second Grade: "))
Grade3 = int(input("Enter Student's Third Grade: "))
Grade4 = int(input("Enter Student's Fourth Grade: "))

print ("Total Grade Average: %G" % (Grade1+Grade2+Grade3+Grade4/4))

print ("%s has:" % (Student))

if Grade1+Grade2+Grade3+Grade4/4 < 40:
print ("Failed!")
if Grade1+Grade2+Grade3+Grade4/4 > 40:
print ("Passed!")
Was it helpful?

Solution

Change

Grade1+Grade2+Grade3+Grade4/4

to

(Grade1+Grade2+Grade3+Grade4)/4

See the difference here:

>>> 1 + 2 +3 +4/4
7
>>> (1+2+3+4)/4
2
>>> 

In the first case, the value is being evaluated as

Grade1+Grade2+Grade3+(Grade4/4)

What you want is

(Grade1+Grade2+Grade3+Grade4)/4

Consider extracting it as a local variable.

#FinalGrade
Student = str(input("Student Name: "))
Grade1 = int(input("Enter Student's First Grade: "))
Grade2 = int(input("Enter Student's Second Grade: "))
Grade3 = int(input("Enter Student's Third Grade: "))
Grade4 = int(input("Enter Student's Fourth Grade: "))

average =  (Grade1+Grade2+Grade3+Grade4 )/4
print ("Total Grade Average: %G" % (average))

print ("%s has:" % (Student))

if average < 40:
    print ("Failed!")
if average > 40:
    print ("Passed!")

#what if average == 40 ?

To enter everything on the same line,

passed_or_failed = "Passed"
if average < 40:
    passed_or_failed = 'Failed'

print ("%s has: %s" % (Student, passed_or_failed))

OTHER TIPS

It's not python. You need to understand the rules of precedence for Math operators.

You're only dividing Grade4 by 4, and not the sum of the grades.

Because of order of operations, what's actually being evaluated is

Grade1 + Grade2 + Grade3 + (Grade4 / 4)

To fix this, use parentheses around the grades or sum them separately:

gradeAvg = (Grade1 + Grade2 + Grade3 + Grade4) / 4

gradeSum = Grade1 + Grade2 + Grade3 + Grade4
gradeAvg = gradeSum / 4
if (Grade1+Grade2+Grade3+Grade4)/4 < 40:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top