tess123
tess123

Reputation: 11

calculating mean doesn't work

The code produces: You gave me the following numbers: 1 2 3 . When the mean is calculated it equals 0 . I need the answer to be 2.

def get_numbers():
    print "Enter any numbers, when you are finished press q   "
    my_list = []
    while True:
        number = raw_input()
        if number != "q":
            num = int(number)
            my_list.append(num)
        else:
            return my_list


def add():
    the_list = get_numbers()
    total = 0
    for i in the_list:
        total = total*i
        total = total/len(the_list)
    print "You gave me the following numbers:",
    for x in the_list:
        y = str(x)
        print y,
    print ".", "When the mean is calculated it equals", total, "."

add()

Upvotes: 0

Views: 68

Answers (1)

carlosdc
carlosdc

Reputation: 12142

The core problem you have is that you should be doing:

total = 0
for i in the_list:
    total = total+i
total = float(total)/len(the_list)

you need to add the numbers not multiply them and then divide into the length of the list at the end of the iteration.

There are also a variety of other issues with your code:

  • The name add really doesn't say anything about what it does
  • You should probably also separate the I/O (querying the user, printing the results) from the computation (calculating the mean).

This version addresses those issues:

def get_numbers():
    print "Enter any numbers, when you are finished press q   "
    my_list = []
    while True:
        number = raw_input()
        if number != "q":
            num = int(number)
            my_list.append(num)
        else:
            return my_list

def mean(l):
    total = 0
    for i in l:
        total = total + i
    r = float(total)/len(l)
    return r 

def main():
    the_list = get_numbers()
    print "You gave me the following numbers:",
    for x in the_list:
        y = str(x)
        print y,
    print ".", "When the mean is calculated it equals", mean(the_list), "."


main()

Upvotes: 2

Related Questions