This Question have 3 answers right now.

Why is my protected loop erroring?

Question!

I have this script

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

As of now, file equals ["clear", "exit"] and i equals 0.

When I run this script, it errors like this

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

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?

By : bjskistad


Answers

my loop is protected

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

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

while i < len(line) and not line[i] == " ":
    obj += line[i]
    i += 1

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

while not line[i] == " ":
    obj += line[i]
    i += 1
    if i == len(line):
        break


Your loop is not "safe", "break" only breaks inner 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).

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
By : lejlot


If I am reading this correctly, Message would contain a List<MessageUser>.

If that's the case then this should get you close:

var List<Message> messages = 
    ( from m 
      in db.Messages 
      where 
          m.UserID == userid || m.MessageUsers.Any(mu => mu.UserID == userID) 
      select m).ToList();
By : Sam Axe


Video about Why is my protected loop erroring?