1

I have a trouble with nested for-loop breaking.

The further code suppose to find pixels of certain color, which example contains in opened file with step 50 along x and 20 along y:

im1 = Image.open("C:\\Users\\Poos\\Desktop\\G\\green_pixel.bmp")
A = list(im1.getdata())

x = 0
y = 0

im2 = ImageGrab.grab()
B = list(im2.getdata())

for x in range(0,1024, 50):
    for y in range(0,600, 20):
      if(B != A):
         im3 = im2.crop((x,y,x+1,y+1))
         B = list(im3.getdata())
         print(x, y)

      else:
         print("hooray!")
         break

      break

As soon as the pixel is detected the both loops should break, printing some text.

But the x-loop won't break wherever the outer break is placed, printing my text multiple times.

It seems that I've tried all possible variants for outer break position, but nothing works.

What is the problem here?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Paul Bobyrev
  • 97
  • 3
  • 9

1 Answers1

1

Consider placing the code into a function and use a return statement to break out of all the loops.

def func():
    im1 = Image.open("C:\\Users\\Poos\\Desktop\\G\\green_pixel.bmp")
    A = list(im1.getdata())

    x = 0
    y = 0

    im2 = ImageGrab.grab()
    B = list(im2.getdata())

    for x in range(0,1024, 50):
        for y in range(0,600, 20):
        if(B != A):
            im3 = im2.crop((x,y,x+1,y+1))
            B = list(im3.getdata())
            print(x, y)

        else:
            print("hooray!")
            return

        return
Daffyd
  • 104
  • 7