Mihai
Mihai

Reputation: 2927

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
...

Upvotes: 0

Views: 126

Answers (3)

FlipTack
FlipTack

Reputation: 423

Rather than using a break statement, you can use min(...) to predetermine how many times to loop, for example:

for a in range(min(10, width)):
    for b in range(height):
        print(a, b)

This run 10 times, with values of a from 0 to 9 - unless the width is less than 10, in which case it loops width times.

Upvotes: 2

RemcoGerlich
RemcoGerlich

Reputation: 31260

Move the if outside the inner loop:

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

You only left the inner loop and the out one kept running; so when a reach 11, the inner loop starting printing again.

With a > 10 you didn't have that problem as all inner loops immediately stopped, but they did all get started.

Upvotes: 3

Yeg
Yeg

Reputation: 424

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.

Upvotes: 3

Related Questions