tags:

views:

213

answers:

3

Hi everyone,

I have a written a loop for and if condition and I want to break to loop completely when if gets satisfied.

while count:
    i=0
    for line in read_record:
        #print str.strip(count[1:28])
        #print str.strip(read_record[i])
        if string.find(str.strip(read_record[i]),str.strip(count[1:28]))>0:
            code=str.strip(read_record[i+19])+str.strip(read_record[i+20])
            print code[25:]
            break

        i=i+1

So here if the if string.find condition gets satisfied I want to go to while loop flow. Please tell me what will be the best place to break and how should I modify the program so that once the if condition is satisfied I am out of the loop and start again with while loop.

A: 

Based on what you've written, your code does just that. Since the for loop is the last part of the while loop, breaking it will go right to the next iteration of the while loop.

If you do have more code in the while loop that you've omitted, then moving it into the for loop's else clause will cause it to run only if the for loop doesn't break:

for i in someit:
  ...
else:
  print 'for loop did not break'

Just one stylistic issue though. Instead of maintaining your own counter, use:

for i, line in enumerate(read_record):
Ignacio Vazquez-Abrams
A: 

Your code already does that. Though it is unclear why do you need nested loops and what are those magic numbers for. Here's your code refactored a bit for readability:

while count: # while len(count) > 0 
    for i, record in enumerate(read_record):        
        if count[1:28].strip() in record:
           code= ''.join(map(str.strip, read_record[i+19:i+21]))
           print code[25:]
           break
    else:
        # no break occurred
        pass
J.F. Sebastian
Thanks it worked
kdev
A: 

I wonder if you are really doing what you intend to with i. Maybe you want something like this:

while count: 
    for line in read_record: 
        if str.strip(count[1:28]) in read_record:
            code=str.strip(read_record[:20])+str.strip(read_record[20:]) 
            print code[25:]
            break
Gabe
Thanks it helped me
kdev