7/9 Proper indention issue

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

This code works properly. My question is how come the 2nd variance line (variance /= float(len(scores))) has only one indention while the 1st variance line (variance += (average - score) ** 2) has 2 indention, shouldnt both have the same amount of indention?

Also, why does the answer change even with the amount of indention? one indention only in the 2nd code amounts to 334 which is right while two indention results in 69 whcih is wrong. can someone explain how this works.

thank you very much

Think about it like this, if you do not have proper indentation the code is out of scope, this is akin to you being unable to see it. When you change scope level you have to change your code to work on the intended level of scope.

If you fail to do this then your code will create local variables to that scope which will not affect the next higher scope.

Make sense?

ahh gets. ok thanks. will try this more out to see.

Can you explain me this line of code?

variance /= float(len(scores))

What is this: /= ?

variance /= float(len(scores))

“/=” in this is simply saying variance = variance / float(len(scores))

if it was *= it would look like variance = variance * float(len(scores))

you can do += -= *= /=… just a way to pass the variable name so you don’t have to type it

can someone confirm if you can do x **= y ?

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

zeziba, your indentation is wrong on the line
variance /= float(len(scores))
It nees to be outside the for loop! :grinning:

5 Likes

yes you right marshyman…it happend with mine too…finally i found my eror…thanks…:grin:

Thank you for spotting this.

Why it’s out of the loop?And how did you know?