pythonfor-loopbreak

Breaking outside the loop


Using a > 10 breaks the loop as expected, however a == 10 doesn't. Why is this happening? I am using Python 3.5:

from PIL import Image

im = Image.open('1.jpg')
px = im.load()
width, height = im.size

for a in range(width):
   for b in range(height):
      if a == 10:
         break
      print(a, b)

I am trying to stop the iteration when the image width has reached 10. The output:

...
9 477
9 478
9 479
10 0
10 1
10 2
10 3
...

Solution

  • You should put the a == 10 in the outer loop because now it will only break the inner loop.

    for a in range(width):
       if a == 10:
          break
       for b in range(height):
          print(a, b)
    

    Depending on your needs, you might want to put it behind the for b in range(.. loop.