This program returns the population for one given state but I'm trying to alter it so I can get the mean of all the states in the file but I have no clue how I should go about doing this. If someone could explain how to get the function to return the population of all the states I could take it from there.
file = open(getMediaPath("population_state_reduced (2).csv"),"rt")
lines = file.readlines()
for line in lines:
parts = line.split(",")
if parts == s:
You need to first collect the population of all the states. The population is in position 5. Right now your function just returns it, it matches the state (which is position 4).
So you can return the sum of the population, or just a list of all the states and their population.
Here is how to return a list of tuples, with the state and its population:
def findpop(state=None): with open(getMediaPath("population_state_reduced (2).csv"),"rt") as f: if state is None: return [(parts, int(parts) for parts in line.split(',') for line in f] else: for line in f: parts = line.split(',') if parts == state.capitalize(): return int(parts)
Now when you call this function without a state, it will return a list of all states and their population.
If you call it with a specific state, it will return only that state's population.