Incorrect output when averaging in python

Viewed 68

There is no error appearing in this python code but the output is incorrect. This is a code about calculating the average marks of a student.

english_1 = 22
urdu_1 = 23
maths_1 = 15
science_1 = 18
social_1 = 21

english_2 = 10
urdu_2 = 22
maths_2 = 13
science_2 = 25
social_2 = 11
def average_marks(english, urdu, maths, science, social):
    average = english + urdu + maths + science + social / 5
    print("average marks of student")
    print(average)
result1 = average_marks(english_1, urdu_1, maths_1, science_1, social_1)
result2 = average_marks(english_2, urdu_2, maths_2, science_2, social_2)

this is the output

average marks of student 82.2 average marks of student 72.2

If you can pls help i am a beginner. Thank You!

3 Answers

You are missing parentheses when calculating the average. You want to make the sum first and then make the division:

average = (english + urdu + maths + science + social) / 5

Hopefully I was of any help

Your code looks good to me but one thing Try setting result1 to a double or a float instead of a int therefore when python writes the result it will not encounter any restrictions and add parentheses around lie this

(english + math + science) / # of items

Solution

'Order of Operation' shows that division takes procedence of addition. Your problem lies within the following:

average = english + urdu + maths + science + social / 5

Using brackets around the addition section of the code, division will be taken out after the brackets. Like so:

average = (english + urdu + maths + science + social) / 5

Further Notes

To tidy your code up a bit, I would suggest reducing positional parameters in the function and nest your results in a dictionary. Like so:

student_results = {'Student1':{'English':22,'Urdu':23,'Maths':15,'Science':18,'Social':21},
                   'Student2':{'English':10,'Urdu':22,'Maths':13,'Science':25,'Social':11}}

def average_marks(results):
    average = sum(results.values()) / len(results)
    return average

for student, results in student_results.items():
    print("The average results for Student {} is {}".format(student, average_marks(results)))
Related