# Program to compute the mean and variance of some numbers
# (user enters number of numbers, then numbers)
# Matt Bishop, ECS 10 Fall 2012
# compute the mean and variancen of the numbers
# parameter: listnum, a list of numbers
def stats(listnum):
# initialize sum
sum = 0
# add each number in list to sum
for i in listnum:
sum += i
# get average
avg = sum / len(listnum)
# now get the sum of the squares of the differences
vartop = 0.0
for i in listnum:
vartop += (i - avg) ** 2
# now, the actual variance
var = vartop / len(listnum)
return avg, var
# read a list of numbers and print the mean and variance
# calls: function mean, stdev
def main():
# prompt for count of numbers to be entered
try:
n = int(input("How many numbers do you want to add? "))
except:
print("Please enter an integer")
return
# error check
if n < 0:
print("Please enter a positive integer")
return
# if n is 0, there is nothing to do
if n == 0:
print("The mean and variance of your numbers are 0")
return
# we have some numbers to add -- do it!
# initialize list variable
numbers = []
# ask user for next number and
# append each number to the list
i = 1
while i <= n:
prompt = "Enter number %d: " % i
try:
k = int(input(prompt))
except:
print("Oops . . . that's not an integer . . . try again")
else:
numbers = numbers + [ k ]
i += 1
# print the statistics
mean, variance = stats(numbers)
# print the standard deviation
print("The mean of your numbers is", mean, "and the variance is", variance)
main()