Computing the average


#1

https://www.codecademy.com/en/courses/python-intermediate-en-7mgOa/1/2?curriculum_id=4f89dab3d788890003000096#

Exercise: Computing the average, exam statistics.

I receive this error message: Oops, try again. grades_average([1, 6, 2, 4]) returned 3 instead of the expected: 3.25

In the console my result turns out to: 80.4230769231 - Which I believe is correct?

Can someone please explain what I need to change? Because I think I'm getting the correct answer, I don't really understand the reason for the error message, thank you!

Here is my code below:

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(scores):
    total = 0
    for score in scores:
        total = total + score
    return total

def grades_average(scores):
    return grades_sum(scores) /len(scores) 

print grades_average(grades) #80.4230769231


#2

In Python 2 this might possibly return an integer. In your grades_sum function, set total to a float:

total = 0.0

or

total = float(0)

Then your sum will return as a float.


#3

Thank you so much for the quick response.

I changed my total to a float: total = 0.0 and it worked perfectly. That was so simple, I wish I knew how to recognise these subtle changes!

Thank you very much.


#4

In Python 2, integer division returns an integer. In Python 3 it returns a float.

# version2
print 1 / 2      # 0

# version 3
print (1 / 2)    # 0.5

When working in these lessons, Python 2 syntax and results apply. If you need your return value to be a float, then declare it.

Something to keep in mind, if we declare the entire quotient a float, it may be rounded (floored) first.

float ((5 + 4) / 2)    # 4.0

float (5 + 4) / 2      # 4.5

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.