Python Forum

Full Version: problem with while statement.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I am new to python and cant seem to find an answer to my question.Here is what i am trying to do.

I want to make a loop that for example lastst for 10 seconds. Within those 10 sec I want to find an image, if that image is not found within those 10 sec i want it to run the else statement.

Here is what i have now.
[attachment=1505]

import pyautogui
import time

t_end = time.time() + 10
while time.time() < t_end:
    if pyautogui.locateCenterOnScreen('image.png') is not None:
        print("found")
    else:
        print("Not found within the time frame")
See the following link to where this was answered before by using the parameter minSearchTime
https://python-forum.io/thread-35062-pos...#pid147856
It is still good to know why your while loop didn't work since this is a useful pattern.
import pyautogui
import time
 
t_end = time.time() + 10
while time.time() < t_end:
    if pyautogui.locateCenterOnScreen('image.png') is not None:
        print("found")
        break
else:
    print("Not found within the time frame")
The difference is that the "else" portion of the loop is only evaluated when the loop is complete, and only if the loop reached completion by meeting the end condition (time.time() >= t_end) and not the break statement.
Thank you all for the help it worked XD.
SOLVED.