[Python-Help] (fwd)

Craig Ringer craig at postnewspapers.com.au
Sun Dec 5 10:40:41 CET 2004


On Sun, 2004-12-05 at 13:07, Alfred Canoy wrote:

>       a.. Compute the average of a list of numbers
>       b.. Finds the statistical median value of a list of numbers
>       c.. Finds the mode of a list of numbers
> 

> count = 0
> sum = 0
> number = 1
> 
> print 'Enter 0 to exit the loop'
> while number != 0:
>     number = input ('Enter a number: ')
>     count = count + 1
>     sum = sum + number
> count = count -1
> print ' The average is:', sum/count

It looks to me like you'd be better off reading each input number into a
list. (tip: in the interactive interpreter, run 'help(list)' ). Once you
have a list, you can perform all sorts of computations on it to
determine the information you need.

>>> from __future__ import division
>>> x = []
>>> x.append(1)
>>> x
[1]
>>> x.append(5)
>>> x
[1,5]
>>> sum(x)
6
>>> sum(x) / len(x)
3

As you can see, it's much easier to work with data in lists. Some of the
other methods, like list.sort() and list "slices" will also be useful to
you, but I'll let you figure out the details ;-) . Remember that Python
is rather well documented, so that (usually) once you know what you need
you can find out about it...

--
Craig Ringer




More information about the Python-list mailing list