Finding average in a file
<p>One of the things I'm supposed to do is find the average inflation from data in a file I was given. It gives the <code>year</code>, <code>interest</code>, and <code>inflation</code>, with all the numbers below it. Looks something like this.</p>

<pre><code>year interest inflation
1900  4.61    8.1
</code></pre>

<p>This goes on quite a bit further, all the way to 2008. I've made some progress with some help, courtesy of germancoder. I'm still stuck though.</p>

<p>Here's what the code looks like so far.</p>

<pre><code>def myTest(file):
     with open ('filename', 'r') as f:
          inflation = []
          header = 1
          for line in f:
               if header !=1:
                    infl = line.split(",")[2]
                    inflation.append(float(infl))
                    header += 1

           avgInflation = sum(inflation)/len(inflation)

     return avgInflation
</code></pre>

<p>The problem , I think, was that the year interest inflation at the top was causing problems. 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 should do now?</p>

<p>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 (",")</p>

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

<p>Also you are reading the lines in the file incorrectly. I think you are wanting to read them as lines using <code>f.readlines()</code>?</p>

<pre><code>def myTest(file):
     with open ('filename', 'r') as f:
          lines = f.readlines() &lt;--- 2 
          inflation = []
          header = 1
          for line in lines:
               if header !=1:
                    infl = line.split(",")[2]
                    inflation.append(float(infl))
               header += 1 &lt;--- 1 

           avgInflation = sum(inflation)/len(inflation)

     return avgInflation
</code></pre>

python average mean