How do I calculate a mean with python?

W

William Bryant

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?
 
J

Jugurtha Hadjar

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?


Hello, William..

How about you try to execute one bit of your program, and if that works,
try to add to it.

Try

list = [15, 6]
list.count(1)

And see if what it gives you back is what you expected. If not, why ?
 
S

Steven D'Aprano

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?

Let me start by saying that the above is not "best practice" for how to
write functions, and I'll explain why later, but for now I'll just fix
the problem with the calculation.

You have List = [15, 6, 6, 7, 8, 9, 40] and then the mean function walks
through each of the items 15, 6, 6, 7, ... counting how many times that
item is found:

for i in List:
thecount = List.count(i)
thesum = sum(List)


So the first time, i gets the value 15, thecount calculates
List.count(15) which is 1, thesum calculates sum(List) which is 91, and
the end of the loop is reached.

The second time around, i gets the value 6, then thecount calculates
List.count(6) which is 2, thesum calculates sum(List) *again*, which is
still 91, and the end of the loop is reached.

Third time around, i gets the value 6 again, thecount again gets the
value 2, thesum yet again sums up List which still hasn't changed, so yet
again gets 91.

And so on, and so on, until the last iteration, where i gets the value
40, thecount calculates List.count(40) which is 1, thesum re-calculates
the sum yet again, still getting the exact same result 91, and finally
the for-loop comes to an end.

Now the final calculation occurs:

themean = thesum/thecount

which is 91/1 or just 91.

What do you actually want? It's much simpler: you want to count the
*total* number of items, 7, not by counting each item individually. The
total number of items is given by the length of the list:

len(List)

returns 7. And you want to sum the list once, there's no need to sum it 7
times. So the first step is to get rid of the for-loop, just calculate
thesum = sum(List) once, and thecount = len(List) once.

Once you've done that, please write back with your new code, because I
think there will be some more improvements to be made.
 
C

Cameron Simpson

| 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,
 
M

MRAB

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).
 
J

Jugurtha Hadjar

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?

You want to compute the arithmetic mean, I suppose .. Which is the sum
of all, divided by the number of samples. i.e: If you have n numbers or
elements, your mean (arithmetic) would be mean = sum(elements)/n. Right ?

And then, n also doesn't need to be in the loop and list.count(i) gives
the occurrences of i in your list, which you don't need.

list.count(15) gives 1.
thesum/list.count(15) doesn't change.
 
D

Dave Angel

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?

Besides all the other comments, you also neglected calling this
function.
 
T

Travis Griggs

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?

You've had a number of interesting and good responses, some holding your hand quite a bit, and others differently.

I think there's a different way to learn what's going wrong, that ISN'T mentioned here, and for some people it's a quite effective method of learning. I'm a relatively recent import from the Smalltalk community, where this approach is more prevalent, I wish it were more so in the Python community.

The way I suggest is to use a debugger. The nice thing about a debugger, is that you add a call to mean() at the end, put a breakpoint right there, run, and then you can visually walk through what it's doing. This can help find your bug, but probably also clarify how Python works in the first place. I use pycharm (anyone can use it for free). And there are probably others for free as well.
 
W

William Bryant

Sorry guys, I didn't read anything u said. Because I just figured it out on my own :)
I'll read it now. But u can check out my program I have done so far (It works but I think it needs some tidying up.) :)

Thanks!
 
W

William Bryant

'''#*************************************************************************'''
#* Name: Mode-Median-Mean Calculator *#
#* *#
#* Purpose: To calculate the mode, median and mean of a list of numbers *#
#* and the mode of a list of strings because that is what we are *#
#* learning in math atm in school :p *#
#* *#
#* Author: William Bryant *#
#* *#
#* Created: 11/09/2013 *#
#* *#
#* Copyright: (c) William 2013 *#
#* *#
#* Licence: IDK :3 *#
'''**************************************************************************'''



#-----# ~~Import things I am using~~ #-----#

# |
# |
# \/

import time
import itertools



#-----# ~~Variables that I am using, including the list.~~ #-----#

# |
# |
# \/

List = []
NumberOfXItems = []
themode = None
themean = None
count = None

#-----# ~~Functions that I am using.~~ #-----#

# |
# |
# \/

def HMNs():
global TheStr, user_inputHMNs, List_input, List
user_inputHMNs = input("You picked string. This program cannot calculate the mean or median, but it can calculate the mode. :D How many strings are you using in your list? (Can not be a decimal number) \nEnter: ")
user_inputHMNs
time.sleep(1.5)
TheStr = int(user_inputHMNs)
for i in range(TheStr):
List_input = input("Enter your strings. (One in each input field): ")
List.append(List_input)
print("Your list -> ", List)
if List.count == int(user_inputHMNs):
break
mode()
mean()
print("\n*Mode*:", themode)
print("*Median*:", "<Coming soon!>\n")
print("*Mean*:", themean)

def HMNn():
global TheNum, user_inputHMNn, List_input, List
user_inputHMNn = input("You picked number. :D How many numbers are you using in your list? (Can not be a decimal number) \nEnter: ")
user_inputHMNn
time.sleep(1.5)
TheNum = int(user_inputHMNn)
for i in range(TheNum):
List_input = input("Enter your numbers. (One in each input field): ")
List_input = int(List_input)
List.append(List_input)
print("\nYour list -> ", List)
if List.count == int(user_inputHMNn):
break
mode()
mean()
print("\n*Mode*:", themode)
print("*Median*:", "<Coming soon!>")
print("*Mean*:", themean)

def NOS():
while True: # Loops forever (until the break)
answer = input("Does your list contain a number or a string? \nEnter: ")
answer = answer.lower()
if answer in ("string", "str", "s"):
HMNs()
break
elif answer in ("number", "num", "n", "int"):
HMNn()
break
elif answer in ("quit", "q"):
break # Exits the while loop
else:
print("You did not enter a valid field, :p Sorry. \nEnter: ")
time.sleep(1.5)

def mean():
global themean
thecount = []
for i in List:
thecount.append(List.count(i))
thesum = sum(List)
thecount = sum(thecount)
themean = thesum / thecount

def mode():
global themode
max_occurrences = 0
themode = None
for i in List:
thecount = List.count(i)
if thecount > max_occurrences:
max_occurrences = thecount
themode = i



#-----# ~~The functions which need calling~~ #-----#

# |
# |
# \/

NOS()
 
W

William Bryant

Ok I think I've fixed it thanks I read everything.

'''**************************************************************************'''
#* Name: Mode-Median-Mean Calculator *#
#* *#
#* Purpose: To calculate the mode, median and mean of a list of numbers *#
#* and the mode of a list of strings because that is what we are *#
#* learning in math atm in school :p *#
#* *#
#* Author: William Bryant *#
#* *#
#* Created: 11/09/2013 *#
#* *#
#* Copyright: (c) William 2013 *#
#* *#
#* Licence: IDK :3 *#
'''**************************************************************************'''



#-----# ~~Import things I am using~~ #-----#

# |
# |
# \/

import time
import itertools



#-----# ~~Variables that I am using, including the list.~~ #-----#

# |
# |
# \/

List = []
NumberOfXItems = []

#-----# ~~Functions that I am using.~~ #-----#

# |
# |
# \/

def HMNs():
global TheStr, user_inputHMNs, List_input, List
user_inputHMNs = input("You picked string. This program cannot calculate the mean or median, but it can calculate the mode. :D How many strings are you using in your list? (Can not be a decimal number) \nEnter: ")
user_inputHMNs
time.sleep(1.5)
TheStr = int(user_inputHMNs)
for i in range(TheStr):
List_input = input("Enter your strings. (One in each input field): ")
List.append(List_input)
print("Your list -> ", List)
if List.count == int(user_inputHMNs):
break
print("\n*Mode*:", mode())
print("*Median*:", "<Coming soon!>\n")
print("*Mean*:", mean())

def HMNn():
global TheNum, user_inputHMNn, List_input, List
user_inputHMNn = input("You picked number. :D How many numbers are you using in your list? (Can not be a decimal number) \nEnter: ")
user_inputHMNn
time.sleep(1.5)
TheNum = int(user_inputHMNn)
for i in range(TheNum):
List_input = input("Enter your numbers. (One in each input field): ")
List_input = int(List_input)
List.append(List_input)
print("\nYour list -> ", List)
if List.count == int(user_inputHMNn):
break
print("\n*Mode*:", mode())
print("*Median*:", "<Coming soon!>")
print("*Mean*:", mean())

def NOS():
while True: # Loops forever (until the break)
answer = input("Does your list contain a number or a string? \nEnter: ")
answer = answer.lower()
if answer in ("string", "str", "s"):
HMNs()
break
elif answer in ("number", "num", "n", "int"):
HMNn()
break
elif answer in ("quit", "q"):
break # Exits the while loop
else:
print("You did not enter a valid field, :p Sorry. \nEnter: ")
time.sleep(1.5)

def mean():
thesum = sum(List)
amount = len(List)
themean = thesum / amount
return themean

def mode():
max_occurrences = 0
themode = None
for i in List:
thecount = List.count(i)
if thecount > max_occurrences:
max_occurrences = thecount
themode = i
return themode



#-----# ~~The functions which need calling~~ #-----#

# |
# |
# \/

NOS()
 
J

Joel Goldstick

Ok I think I've fixed it thanks I read everything.


'''**************************************************************************'''
#* Name: Mode-Median-Mean Calculator
*#
#*
*#
#* Purpose: To calculate the mode, median and mean of a list of
numbers *#
#* and the mode of a list of strings because that is what we
are *#
#* learning in math atm in school :p
*#
#*
*#
#* Author: William Bryant
*#
#*
*#
#* Created: 11/09/2013
*#
#*
*#
#* Copyright: (c) William 2013
*#
#*
*#
#* Licence: IDK :3
*#

'''**************************************************************************'''

The above comments are a mess. In python, use docstrings -- put 3 quotes
in front of all the documentation, and 3 at the end like:
"""
Name: Mode-Median-Mean Calculator
Purpose: To calculate the mode, median and mean of a list of
numbers *#
"""

There is a utility called pydoc that will pull all docstrings from a module
and produce nice documentation. So better to learn this style early

#-----# ~~Import things I am using~~
#-----#

# |
# |
# \/

import time
import itertools

I don't think you use itertools, so remove the reference

#-----# ~~Variables that I am using, including the list.~~
#-----#

# |
# |
# \/

List = []
NumberOfXItems = []

Using global variables is a very bad idea. Since you seem to be a novice,
I'm wondering where you even learned about global variables. If your
instructor taught you, then (s)he should look for a new line of work.
Using globals promotes lazy thought, makes debugging impossible in any
reasonably large piece of code. Google about that. Its important


#-----# ~~Functions that I am using.~~
#-----#

# |
# |
# \/

Use better names. What does HMNs mean? This function asks the user to
input a list of strings or numbers. It is almost identical to HMNn to that
point that they should be combined most likely.

def HMNs():
"""
Here you should write about the function -- what it does, what is
needs passed to it, and what it returns.
"""



global TheStr, user_inputHMNs, List_input, List
user_inputHMNs = input("You picked string. This program cannot
calculate the mean or median, but it can calculate the mode. :D How many
strings are you using in your list? (Can not be a decimal number) \nEnter:
")
user_inputHMNs
time.sleep(1.5)
TheStr = int(user_inputHMNs)
for i in range(TheStr):
List_input = input("Enter your strings. (One in each input field):
")
List.append(List_input)
print("Your list -> ", List)
if List.count == int(user_inputHMNs):
break
print("\n*Mode*:", mode())
print("*Median*:", "<Coming soon!>\n")
print("*Mean*:", mean())

def HMNn():
global TheNum, user_inputHMNn, List_input, List
user_inputHMNn = input("You picked number. :D How many numbers are you
using in your list? (Can not be a decimal number) \nEnter: ")
user_inputHMNn
time.sleep(1.5)
TheNum = int(user_inputHMNn)
for i in range(TheNum):
List_input = input("Enter your numbers. (One in each input field):
")
List_input = int(List_input)
List.append(List_input)
print("\nYour list -> ", List)
if List.count == int(user_inputHMNn):
break
print("\n*Mode*:", mode())
print("*Median*:", "<Coming soon!>")
print("*Mean*:", mean())

def NOS():
while True: # Loops forever (until the break)
answer = input("Does your list contain a number or a string?
\nEnter: ")
answer = answer.lower()
if answer in ("string", "str", "s"):
HMNs()
break
elif answer in ("number", "num", "n", "int"):
HMNn()
break
elif answer in ("quit", "q"):
break # Exits the while loop
else:
print("You did not enter a valid field, :p Sorry. \nEnter: ")
time.sleep(1.5)

def mean():
thesum = sum(List)
amount = len(List)
themean = thesum / amount
return themean

def mode():
max_occurrences = 0
themode = None
for i in List:
thecount = List.count(i)
if thecount > max_occurrences:
max_occurrences = thecount
themode = i
return themode



#-----# ~~The functions which need calling~~
#-----#

# |
# |
# \/

NOS()


So, I just added a few criticisms earlier above. To sumarize:
avoid global variables, document functions with docstrings, use really
clear names for variables including function names. If you have code in
two functions that is almost identical, figure out how to make them one
function

good luck
 
M

MRAB

Ok I think I've fixed it thanks I read everything.
[snip]

def HMNs():
global TheStr, user_inputHMNs, List_input, List
user_inputHMNs = input("You picked string. This program cannot calculate the mean or median, but it can calculate the mode. :D How many strings are you using in your list? (Can not be a decimal number) \nEnter: ")

This line doesn't do anything:
user_inputHMNs
time.sleep(1.5)
TheStr = int(user_inputHMNs)
for i in range(TheStr):
List_input = input("Enter your strings. (One in each input field): ")
List.append(List_input)
print("Your list -> ", List)

List.count is a method; it will never equal an integer:
if List.count == int(user_inputHMNs):
break
print("\n*Mode*:", mode())
print("*Median*:", "<Coming soon!>\n")
print("*Mean*:", mean())

def HMNn():
global TheNum, user_inputHMNn, List_input, List
user_inputHMNn = input("You picked number. :D How many numbers are you using in your list? (Can not be a decimal number) \nEnter: ")

This line doesn't do anything:
user_inputHMNn
time.sleep(1.5)
TheNum = int(user_inputHMNn)
for i in range(TheNum):
List_input = input("Enter your numbers. (One in each input field): ")
List_input = int(List_input)
List.append(List_input)
print("\nYour list -> ", List)

List.count is a method; it will never equal an integer:
if List.count == int(user_inputHMNn):
break
print("\n*Mode*:", mode())
print("*Median*:", "<Coming soon!>")
print("*Mean*:", mean())
[snip]
 
W

William Bryant

Thanks to all and @Joel Goldstick, I am learning python through youtube. They explained Global and Local variables to me. :) Thanks for that critisism, it really helps. I am 13 years old and I am looking forward to studing programming in University! :DDDDDD
 
J

Joel Goldstick

Thanks to all and @Joel Goldstick, I am learning python through youtube.
They explained Global and Local variables to me. :) Thanks for that
critisism, it really helps. I am 13 years old and I am looking forward to
studing programming in University! :DDDDDD

Well, learn away. Try the python.org tutorial too. The best way to learn
( I think!) is to find all the tutorials you can and work through those
that suit you. Look at python.org for pages that list many help sites,
including those for beginners. Also, there is a python-tutor mailing
list/newsgroup that may be better for you at your stage of learning. Keep
coming back when you get stuck
 
B

Bryan Britten

William -

I'm also self-teaching myself Python and get stuck quite often, so I understand both the thrill of programming and the frustration. Given your young age and presumably very little exposure to other programming languages, I would highly recommend you check out http://www.Codecademy.com and work through their Python tutorials. It will teach you about the different object types (lists, dicts, tuples, etc) and about things like functions, methods andclasses. I think you'll have a MUCH better understanding of Python that will allow you to choose which YouTube videos to watch much more wisely.

Good luck with your endeavors!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,072
Latest member
trafficcone

Latest Threads

Top