Average age?

This is the place for queries that don't fit in any of the other categories.

Average age?

Postby franca1 » Mon Nov 18, 2013 1:30 pm

Hi everyone :),
I have stuck on average age. If I do like below then it showing me all middle ages for each rows:

Code: Select all
import csv
my_file = open("data.csv","rU")
csvReader = csv.reader(my_file, delimiter = ',')

count = 0
sum_age = 0
age = 0
middle_age = 0
while age >=0:
        for row in csvReader:
                count+=1
                age = int(row[0])
                sum_age += age       
                middle_age = sum_age / count
                print (middle_age)


but I just need total average age and when Im doing like below:

Code: Select all
import csv
my_file = open("data.csv","rU")
csvReader = csv.reader(my_file, delimiter = ',')

count = 0
sum_age = 0
age = 0
middle_age = 0
while age >=0:
        for row in csvReader:
                count+=1
                age = int(row[0])
                sum_age += age       
                middle_age = sum_age / count
        print (middle_age)


then showing error:
age = int(row[0])
IndexError: list index out of range

did any one now what to do to get average age??
Last edited by Mekire on Mon Nov 18, 2013 1:56 pm, edited 1 time in total.
Reason: First post lock. Moved to own topic.
franca1
 
Posts: 1
Joined: Mon Nov 18, 2013 1:09 pm

Re: Average age?

Postby metulburr » Mon Nov 18, 2013 2:18 pm

any one now what to do to get average age??

you can make it a lot easier in python and use python's built-in sum() and len() functions.
Code: Select all
ages = [10,13,15,25,26,44,20]
print( sum(ages) / len(ages) )
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1451
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: micseydel, Yoriz and 5 guests