0

I have a program like this:

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

And test.txt looks like this:

1
ABC
2
CAB
3

The program outputs this:

ABC
CAB

And then it goes into an infinite loop. Is there a way to fix this?

8
  • Is the text file separated line by line? Or is it all one line or comma separated? Also, please post the output of the code before it runs into an infinite loop. Commented Jun 25, 2016 at 3:18
  • 3
    The break is breaking out of the for loop, not the while loop. Commented Jun 25, 2016 at 3:21
  • Yes it is separated line by line, The format didn't come out Commented Jun 25, 2016 at 3:21
  • you know, you can use a debug for that. Commented Jun 25, 2016 at 3:22
  • 1
    Although while 1 is understood, while True is typically better for clarity. Commented Jun 25, 2016 at 3:28

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

0

Add a second break statement on the line after the first break statement, but line it up with your for statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.