Python-Ref > Basic usage > Looping > Breaking from a loop
 
 

<-^^->
Moduly
Knihovní funkce

Breaking from a loop

How to prematurely end a loop.
Sometimes it is useful to end a loop before it ends naturally. It is useful in cases when we need to find the first occurence of some item in a sequence or similar cases.
Expand/Shrink
Zdroj: (break-loop1.py)
  1   # find the first odd number in a sequence
  2   
  3   xs = [2, 4, 10, 13, 16, 10, 7, 5]
  4   
  5   for x in xs:
  6       if x % 2 == 1:
  7           print x
  8           break
  9   
 10       
stdout:
13
Doba běhu: 21.0 ms
When used in combination with a while loop, it can be used to construct very sophisticated conditions for ending the loop.
Expand/Shrink
Zdroj: (break-loop2.py)
  1   x = 0
  2   
  3   while True:     # this would be an endless loop
  4       x = x + 1   # increment x bu 1 in each successive loop
  5       if x % 3 == 0 and x % 7 == 0:   # is x divisible by both 3 and 7?
  6           print x
  7           break   # we jump out of the loop
stdout:
21
Doba běhu: 20.9 ms