Computing the Average - 5/9


#1

Hi,

Can anyone tell me why this does not give the correct result?

As far as I can tell it should give me the correct result but it gives me this “You did not print the correct average. Double-check your code and make sure you print the average!”

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

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

def grades_average(grades_input):
average = grades_sum(grades_input)/float(len(grades_input))

return average

print grades_average(grades)

Thanks in advance!


#2

In order to help you, we’re going to need two things:

  • Your formated code (Alternatively, just post a screenshot of your code)
  • A link to the exercise you are on

#3

There it is, sorry…

https://www.codecademy.com/courses/learn-python/lessons/exam-statistics/exercises/computing-the-average?action=lesson_resume

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

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

  
def grades_average(grades_input):
  average = grades_sum(grades_input)/float(len(grades_input))
  
  return average

print grades_average(grades)

#4

Alright two things,

The first can be found right here:

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

A wise man once said, “A function ends the moment a return key is reached.” In other words, your return statement should not be inside the for loop. It should, instead, be on the same indentation level as your for statement, like so:

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

The second issue can be found here:

def grades_average(grades_input):
    average = grades_sum(grades_input)/float(len(grades_input))
    
    return average

This is great and all, but what’s with that extra line of white-space after your average = statement? It is unnecessary and actually might cause errors. Please get rid of it. Or, better yet, you could just return the statement without creating a variable, like this:

    return grades_sum(grades_input) / float(len(grades_input))

But, that’s entirely up to you.


#5

Thanks!!!
It was the first one messing my results!

The second is just to be easier to read, but I will get rid of it, specially because you are right it is much easier to return the result directly!

Thanks again!


#6

That’s not necessarily true. In python improper whitespace can cause errors.


#7

Thanks for the info, I didnt knew that.


#8

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