简体   繁体   中英

Breaking outside the loop - Python

This might be obvious to others.

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

The code snippet:

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)

Edit: I trying to stop the iteration when the image width has reached 10. The output looks like this:

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM