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>

<p>Your loop is not "safe", "break" only breaks <strong>inner</strong> loop, thus once i==len(line) it goes out of first while, stays in the main for and you try to read out line[i] in "while not line[i] == """ line, which causes you to index outside "line" (since the condition is checked before entering the loop).</p>

<pre><code>for line in file:
    while line[i] == " ":
        if i == len(line):   
            break # THIS executes, thus i == len(line)
        i += 1
    if i == len(line): # this is true, thus nothing happens, pass is no-op
        pass
    while not line[i] == " ": # this executes, and fails since i == len(line)
        if i == len(line):
            break
        obj += line[i]
        i += 1
    print obj
</code></pre>

python while-loop