Why is my protected loop erroring?
<p>I have this script</p>

<pre><code>for line in file:
    while line[i] == " ":
        if i == len(line):
            break
        i += 1
    if i == len(line):
        pass
    while not line[i] == " ":
        if i == len(line):
            break
        obj += line[i]
        i += 1
    print obj
</code></pre>

<p>As of now, <code>file</code> equals <code>["clear", "exit"]</code> and <code>i</code> equals <code>0</code>.</p>

<p>When I run this script, it errors like this</p>

<pre><code>Traceback (most recent call last):
  File "/home/ubuntu/workspace/lib/source.py", line 8, in &lt;module&gt;
    while not line[i] == " ":
IndexError: string index out of range
</code></pre>

<p>I'm pretty sure my loop is protected right, and it should break before this happens. If this the case, then why is it happening?</p>

<blockquote>
  <p>my loop is protected</p>
</blockquote>

<p>No it isn't. The condition on the <code>while</code> has to be evaluated first before reaching the body of the loop where the <em>protection</em> <code>if</code> condition is.</p>

<p>To be sure <code>i</code> does not exceed the length of the list, move the condition on the <code>if</code> and make it the first condition on the <code>while</code>:</p>

<pre><code>while i &lt; len(line) and not line[i] == " ":
    obj += line[i]
    i += 1
</code></pre>

<hr>

<p>Otherwise you could move the <code>if</code> block after the update of <code>i</code> so the condition is evaluated before that of the next iteration of <code>while</code>:</p>

<pre><code>while not line[i] == " ":
    obj += line[i]
    i += 1
    if i == len(line):
        break
</code></pre>

python while-loop