简体   繁体   English

打破循环-Python

[英]Breaking outside the loop - Python

This might be obvious to others. 这对其他人可能是显而易见的。

Using a > 10 breaks the loop as expected, however a == 10 doesn't. 使用a > 10会按预期中断loop ,但是a == 10则不会。 Why is this happening? 为什么会这样呢? I am using Python 3.5 . 我正在使用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: 编辑:当图像宽度达到10时,我试图停止迭代。输出看起来像这样:

...
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. 您应该将a == 10放在外部循环中,因为现在它只会破坏内部循环。

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. 根据您的需要,您可能希望将其放在for b in range(..循环)中for b in range(..后面。

Move the if outside the inner loop: if移到内部循环之外:

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. 因此当到达11时,内部循环将再次开始打印。

With a > 10 you didn't have that problem as all inner loops immediately stopped, but they did all get started. a > 10您没有问题,因为所有内部循环都立即停止了,但它们确实都开始了。

Rather than using a break statement, you can use min(...) to predetermine how many times to loop, for example: 您可以使用min(...)预先确定要循环多少次,而不是使用break语句,例如:

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. 此运行10次,具有值a从0到9 -除非该宽度小于10,在这种情况下它循环width次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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