Error with .readlines()[n]
<p>I'm a beginner with Python.
I tried to solve the problem: "If we have a file containing &lt;1000 lines, how to print only the odd-numbered lines? ". That's my code:</p>

<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
   n=1
   num_lines=sum(1 for line in f)
   while n&lt;num_lines:
         if n/2!=0:
                 a=f.readlines()[n]
                 print(a)
         break
    n=n+2
</code></pre>

<p>where <em>n</em> is a counter and <em>num_lines</em> calculates how many lines the file contains. 
But when  I try to execute the code, it says: </p>

<pre><code>"a=f.readlines()[n]
 IndexError: list index out of range"
</code></pre>

<p>Why it doesn't recognize <em>n</em> as a counter?</p>

<p>This code will do exactly as you asked:</p>

<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
    for i, line in enumerate(f.readlines()):   # Iterate over each line and add an index (i) to it.
        if i % 2 == 0:       # i starts at 0 in python, so if i is even, the line is odd
            print(line)
</code></pre>

<p>To explain what happens in your code:</p>

<p>A file can only be read through once. After that is has to be closed and reopened again. </p>

<p>You first iterate over the entire file in <code>num_lines=sum(1 for line in f)</code>. Now the object <code>f</code> is empty. </p>

<p>If n is odd however, you call <code>f.readlines()</code>. This will go through all the lines again, but none are left in <code>f</code>. So every time n is odd, you go through the entire file. It is faster to go through it once (as in the solutions offered to your question).</p>

python python-3.x while-loop