How do I calculate a mean with python?

Cameron Simpson cs at zip.com.au
Mon Sep 16 19:59:45 EDT 2013


On 16Sep2013 16:33, William Bryant <gogobebe2 at gmail.com> 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
|     for i in List:
|         thecount = List.count(i)
|         thesum = sum(List)
|     themean = thesum / thecount
| 
| Why doesn't this work?

Well:

  - always include the output you get from your program, and say
    why you think it is incorrect

  - just style: we tend to name variables in lower case in Python, and
    classes with an upper case letter; "List" is a bit odd (but
    "list" is taken; how about "values"?)

  - more than style: WHY are you using global variables; just return the mean
    from the function!

  - teh variable "List" inside the function is _local_; your function does not
    accept a parameter

  - sum(List) sums the whole list
    you run it many times
    why?

  - what do you think "count()" does?

  - you should print i, thecount and thesum on each iteration of
    the list; it will help you see what your function is doing, and
    therefore to figure out what it is doing wrong

I would write a mean like this:

    def mean(values):
      return sum(values) / len(values)

There are circumstances where that is simplistic, but it is the classic
definition of the mean.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

Microsoft Mail: as far from RFC-822 as you can get and still pretend to care.
      - Abby Franquemont-Guillory <abbyfg at tezcat.com>



More information about the Python-list mailing list