Terrence Rozay - 9 months ago 65

Python Question

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.

`def findpop(state):`

s= state.capitalize()

file = open(getMediaPath("population_state_reduced (2).csv"),"rt")

lines = file.readlines()

file.close()

for line in lines:

parts = line.split(",")

if parts[4] == s:

return int(parts[5])

return -1

Answer Source

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[4], int(parts[5]) for parts in line.split(',') for line in f]
else:
for line in f:
parts = line.split(',')
if parts[4] == state.capitalize():
return int(parts[5])
```

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.