9/7 Variance working with pycharm but error in code academy


#1



Code working in pycharm but throwing error in codeacademy page. Any help appreciated.

Python 9/7

Getting this type of error messages

Oops, try again. grades_variance([3, 2, 2, 3, 1, 2]) returned None instead of the expected: 0.4722222222

In pycharm I am getting this result
/usr/local/bin/python /Users/xxxx/Documents/python/python/average_variance1.py
0.47222222222222215

Process finished with exit code 0


grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
    for grade in grades:
        print(grade)

def grades_sum(grades):
    total = 0
    for grade in grades:
        total += grade
    return total

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


def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        variance += (average - score) ** 2
    result = variance / float(len(scores))
    print(result)


#2

i think you have to replace print by return so the function return result not print it ,

def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        variance += (average - score) ** 2
    result = variance / float(len(scores))
    return result

#3

Just like what @azazaz mentioned, you shouldn't use a print to "bring back" a value from a function but a return.
The print statement will only print something on the screen so the user can see while a return statement will make the program return to where the function was called, bring back a value (if there's any if not, None) and continue with the execution of the code.

Your code works but if I need to work with the value obtained from calling the function grades_variance I won't be able to get it, since you're not returning it.


#4

Thank you azazaz & g4be very much for your help. It worked. The final code looks like this.

def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        variance += (average - score) ** 2
    result = variance / float(len(scores))
    return result

print(grades_variance(grades))