# What's wrong with my code? EXAM STATISTICS | Python

#1

Hey guys!

``````# Instructions
# On line 18, define a new function called grades_variance() that accepts one argument, scores, a list.
# First, create a variable average and store the result of calling grades_average(scores).
# Next, create another variable variance and set it to zero. We will use this as a rolling sum.
# for each score in scores: Compute its squared difference: (average - score) ** 2 and add that to variance.
# Divide the total variance by the number of scores.
# Then, return that result.

Here's my code:

variance = 0
for score in scores:
variance += (average - score) ** 2
return variance / len(scores)

``````

I don’t know what’s wrong with my code. I tried using a new variable and it worked:

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

What’s wrong with the first code? Thanks for the help!

#2

but the newvar is not what makes it work

by default, a function returns none at the end of the function. If we want return something else at the end of the function, we can use the return keyword. Thus, when a return keyword is reached, the function ends

so difference between the two codes, is the indent of return. In the first program, return is nested inside the for loop, which will cause the function to end in the first iteration of the loop, causing an incorrect calculation.

#3

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