Bill Wang Bill Wang - 1 year ago 71
Python Question

While Loop Not Breaking In Python

I have a program like this:

def read():
while 1:
for line in temp1:
if event in line:
elif date in line:
elif ending in line:
print 'End of file'
event = '1'
date = '2'
ending = '3'
temp1 = open('test.txt')

And test.txt looks like this:


For some reason the while loop is not breaking when the program is at the end of the file

Answer Source

Your break statement only breaks out of the for loop (if it's hit). It doesn't, and indeed, can't break out of the while loop as well. Though I'm not sure what the while loop is there for, since the for loop should iterate over the whole file. Since you're already in a function, you can use a return statement to break out of multiple loops (though it would probably be better to just get rid of the extra loop).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download