1

I have to calculate the standard deviation using loops for a list. This is what I have:

elif user_option == 2:
  stdev= 0
  average = 0
  for val in scores_list:
    diffsquared= (val - average)**2
    sum_diffsquared= diffsquared + val
    stdev= ((sum_diffsquared)/num_scores)**(1/2)
    print(stdev)

I keep on getting the wrong number.

1 Answer 1

2

You have a couple of problems in your code. First, "sum_diffsquared" is being calculated outside of the loop. Secondly, you declare the average as 0. You need to calculate the average first.

import numpy
import scipy

stddev = 0
average = 0
scores = [0,1,2,3,4]
average = numpy.mean(scores) #or calculate it yourself
diffsquared = 0
sum_diffsquared = 0
for val in scores:
  diffsquared = (val-average)**2
  sum_diffsquared = diffsquared + sum_diffsquared
stddev = ((sum_diffsquared)/len(scores))**(1/2) # corrected
print(stddev)
print(numpy.sqrt(numpy.var(scores)))

The output is:

1.41421356237
1.41421356237

Showing that the calculation is now correct.

2
  • What I did is I calculated the average in an elif statement before this elif statement. But for some reason it says that "average" is not defined
    – user300
    Sep 29, 2013 at 20:14
  • You must calculate the average before the corresponding 'if' statement. You should familiarize yourself with the concept of variable scopes ( en.wikipedia.org/wiki/Scope_(computer_science) ). In short, your variable "average" is undefined for that 'elif' scope. If you declare "average" before your 'if/elif' statements, the variable will still be visible through all 'if/elif' scopes.
    – andrew
    Sep 29, 2013 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.