Search code examples
pythonwindowsif-statementpython-3.9

Why is my Python code executing the lines after the if-else statement before the lines within the if-else statement?


I am a beginner at programming on Python. I made a program with Chatgpt that I don't fully understand, but I know that I want to make many more if-else statements without making it complicated with nesting. What can I do besides putting the lines after the if-else within the if-else statement?

import pyautogui
import numpy as np
import cv2
import time

CountGooglyFound = 0

def take_screenshot():
    # Take a screenshot
    screenshot = pyautogui.screenshot()
    # Convert the screenshot to a numpy array for further processing
    screenshot_np = np.array(screenshot)
    return screenshot_np

def search_for_image(image_path, screenshot):
    # Load the image to search for
    image_to_search = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    # Convert the screenshot to grayscale
    screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)
    # Ensure both images have the same data type and depth
    screenshot_gray = np.uint8(screenshot_gray)
    image_to_search = np.uint8(image_to_search)
    # Perform template matching
    result = cv2.matchTemplate(screenshot_gray, image_to_search, cv2.TM_CCOEFF_NORMED)
    # Set a threshold for matching
    threshold = 0.75
    # Get the location of matched regions
    locations = np.where(result >= threshold)
    # Check if the image is found
    if len(locations[0]) > 0:
        return True, list(zip(*locations[::-1]))  # Return coordinates of matched regions
    else:
        return False, None

def main():
    # Take a screenshot and store it in a variable
    screenshot = take_screenshot()

    # Path to the image to search for within the screenshot
    image_path = r'C:\Users\Iris\Desktop\ImageTest\Googly.png'

    # Search for the image within the screenshot
    found, locations = search_for_image(image_path, screenshot)

    if found:
        print("Image found at the following locations:")
        print(locations)
        # Click at point (500,500)
        pyautogui.click(500, 500)
        CountGooglyFound =+ 1
        print(CountGooglyFound)
    else:
        print("Image not found in the screenshot.")
        pyautogui.click(500, 50)
    
pyautogui.click(50, 500)
print(CountGooglyFound)

if __name__ == "__main__":
    main()

I tried this, but pyautogui.click(50, 500) and print(CountGooglyFound) executed before what is in the if or the else statements. Everything else seems to run smoothly since it can detect the image or not detect it.


Solution

  • If I understand your question, you're wondering why this:

        if found:
            print("Image found at the following locations:")
            print(locations)
            # Click at point (500,500)
            pyautogui.click(500, 500)
            CountGooglyFound =+ 1
            print(CountGooglyFound)
        else:
            print("Image not found in the screenshot.")
            pyautogui.click(500, 50)
    

    is executing after these lines:

    pyautogui.click(50, 500)
    print(CountGooglyFound)
    

    If so, notice that the if-statement in question is part of a function definition. It's part of the function main() because it is indented. Everything that's part of a function definition runs when you call a function. Here, you call the function main() in the very last segment.