pythonloopsfor-loopwhile-loop

Python using a for with a while loop


Currently I have this

for word in words:
   print(word)

but now i want to introduce a while loop, to only execute that as long as an image (spinner.png) is located on the screen. like this

while True:

    try:    
       location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
       for word in words:
              print(word)
    except pyautogui.ImageNotFoundException:
       pass

OR like this:

for word in words:

   while True:

    try:    
       location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
       print(word)
    except pyautogui.ImageNotFoundException:
       pass

and looking for the pythonic way also. but confused by reading many kb on break in the inner loop.

I have not tried anything as yet, just want to know the most efficient way to code this

while True:

    try:    
       location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
       for word in words:
              print(word)
    except pyautogui.ImageNotFoundException:
       pass

Solution

  • Heres two Suggestions you could try

    Option 1:

    while True:
        try:    
            location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
            if location:  # Image found
                for word in possible_words:
                    print(word)
                break  # Exit the loop after printing all words once
        except pyautogui.ImageNotFoundException:
            pass
    

    This option prints all words only once after detecting the image ^

    Option 2:

    while True:
        try:    
            location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
            if location:  # Image found
                for word in possible_words:
                    print(word)
            else:
                break  # Exit the loop if the image is no longer found
        except pyautogui.ImageNotFoundException:
            pass
    

    This option prints each word continuously as long as the image is found ^

    You potentially could also try an approach of importing a time module then incorporating the following code:

      except pyautogui.ImageNotFoundException: