Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: exit out of two loops

Tags:

python

  for row in b:     for drug in drug_input:       for brand in brand_names[drug]: 

from the third loop how do i exit the current loop and go to the next value of for row in b: ?

like image 854
Alex Gordon Avatar asked Jul 28 '10 20:07

Alex Gordon


People also ask

How do you exit a nested for loop in Python?

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.

Does break only exit one loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.

Does Break stop all loops Python?

The Python break statement immediately terminates a loop entirely.

How do you break out of a nested while loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.


1 Answers

This one uses a boolean to see if you are done yet:

done = False for x in xs:     for y in ys:         if bad:             done = True             break      if done:         break 

This one will continue if no break was used. The else will be skipped over if there was a break, so it will see the next break. This approach has the benefit of not having to use a variable, but may be harder to read to some.

for x in xs:     for y in ys:         if bad:             break     else:         continue      break 
like image 87
Donald Miner Avatar answered Sep 24 '22 21:09

Donald Miner