Anonymous - 12 days ago 5x
Python Question

# Finding average in a file

One of the things I'm suppose to do is find the average inflation in this file I was given. It give the year, interest and inflation, with all the numbers below it. Looks something like this.

year interest inflation

1900 4.61 8.1

This goes on quite a bit further, all the way to 2008. I've made some progress with some help, curtesy of germancoder. I'm still stuck though. Here what the code looks like so far.

``````def myTest(file):
with open ('filename', 'r') as f:
inflation = []
for line in f:
infl = line.split(",")[2]
inflation.append(float(infl))

avgInflation = sum(inflation)/len(inflation)

return avgInflation
``````

See the problem was that the year interest inflation at the top was causing problems I think, so with help I added stuff to the code, but I'm still getting an error. It says division by zero error, line 11. Any thoughts on what I do now?
Should mention that I'm extremely new to programming, so I apologize for all the confusion. Let me add this too, the actual file name is Inflation.csv. I made a simple program myself which prints it in the interpreter, which shows it separated by commas, hence why I did (",")

Your condition for appending to the header will never be met as `header += 1` is under the condition `header != 1` and `header`'s initial value is `1`. Therefore you are looping over the array and doing nothing. At the end of your method where you calculate the average, your `inflation` list is still empty so `len(inflation)` resolves to `0`.

Also you are reading the lines in the file incorrectly. I think you are wanting to read them as lines using `f.readlines()`?

``````def myTest(file):
with open ('filename', 'r') as f:
inflation = []