Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Leave Loop Early

Tags:

python

loops

How do I leave a loop early in python?

for a in b:     if criteria in list1:         print "oh no"         #Force loop i.e. force next iteration without going on     someList.append(a) 

Also, in java you can break out of a loop, is there an equivalent in Python?

like image 215
Federer Avatar asked Feb 02 '10 13:02

Federer


People also ask

How do you exit a loop early in Python?

In Python, the keyword break causes the program to exit a loop early. break causes the program to jump out of for loops even if the for loop hasn't run the specified number of times. break causes the program to jump out of while loops even if the logical condition that defines the loop is still True .

How do you exit a loop early?

You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.


2 Answers

continue and break is what you want. Python works identically to Java/C++ in this regard.

like image 64
Max Shawabkeh Avatar answered Sep 26 '22 02:09

Max Shawabkeh


Firstly, bear in mind it might be possible to do what you want with a list comprehension. So you might be able to use something like:

somelist = [a for a in b if not a.criteria in otherlist] 

If you want to leave a loop early in Python you can use break, just like in Java.

>>> for x in xrange(1,6): ...     print x ...     if x == 2: ...         break ... 1 2 

If you want to start the next iteration of the loop early you use continue, again just as you would in Java.

>>> for x in xrange(1,6): ...     if x == 2: ...         continue ...     print x ... 1 3 4 5 

Here's the documentation for break and continue. This also covers else clauses for loops, which aren't run when you break.

like image 32
Dave Webb Avatar answered Sep 25 '22 02:09

Dave Webb