How do I calculate a mean with python?
MRAB
python at mrabarnett.plus.com
Mon Sep 16 20:01:50 EDT 2013
On 17/09/2013 00:33, William Bryant wrote:
> Hey I am new to python so go easy, but I wanted to know how to make a program that calculates the maen.
>
> List = [15, 6, 6, 7, 8, 9, 40]
> def mean():
> global themean, thesum
You're iterating through every number in the list...
> for i in List:
counting how many times each number occurs in the list:
> thecount = List.count(i)
This line calculates the sum of the numbers on every iteration:
> thesum = sum(List)
This line divides the sum of the numbers by the last count:
> themean = thesum / thecount
>
> Why doesn't this work?
>
It does work; it just doesn't calculate the mean!
What you end up with is:
themean = sum(List) / List.count(40)
What you _really_ want is the sum of the numbers divided by the
number of numbers (i.e. the length of the list).
More information about the Python-list
mailing list