You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码if-else后语句先执行的原因及多条件优化方案

问题解决方案

1. 执行顺序异常的修复

问题原因

你代码里的pyautogui.click(50, 500)和print(CountGooglyFound)属于全局作用域代码,Python解释器会从上到下依次执行这些代码,而main()函数是在if __name__ == "__main__"块里才被调用,因此这两行会先于main内的if-else分支执行。

另外,main函数里的CountGooglyFound =+ 1存在两个问题:一是赋值运算符写错(应为+=而非=+),二是未声明使用全局变量,导致此处会创建局部变量,无法修改全局的CountGooglyFound。

修复方案

将全局作用域的那两行代码移到合适位置,比如需要在main执行后运行,就放到if __name__ == "__main__"块内;同时在main函数开头声明global CountGooglyFound,确保能修改全局变量。

2. 避免嵌套if-else的优化方案

如果要添加更多条件判断且不想增加嵌套复杂度,推荐以下几种方式:

方式一:提前返回(守卫模式)

将每个条件判断放在函数开头,满足条件则执行对应逻辑后直接返回,避免多层嵌套,适合条件互斥的场景。

方式二:字典映射处理多分支

将不同条件对应的操作封装成独立函数,用字典建立条件与函数的映射,直接根据条件调用对应函数,适合条件较多且操作独立的场景。

方式三:拆分逻辑为小函数

将不同条件下的业务逻辑拆分成单独的小函数,让主函数只负责流程控制,可读性更强。

修改后的完整代码示例

以下代码修复了执行顺序问题,并使用提前返回方式优化条件判断结构:

import pyautogui
import numpy as np
import cv2
import time

CountGooglyFound = 0

def take_screenshot():
    screenshot = pyautogui.screenshot()
    return np.array(screenshot)

def search_for_image(image_path, screenshot):
    image_to_search = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)
    screenshot_gray = np.uint8(screenshot_gray)
    image_to_search = np.uint8(image_to_search)
    
    result = cv2.matchTemplate(screenshot_gray, image_to_search, cv2.TM_CCOEFF_NORMED)
    threshold = 0.75
    locations = np.where(result >= threshold)
    
    if len(locations[0]) > 0:
        return True, list(zip(*locations[::-1]))
    else:
        return False, None

def handle_image_found(locations):
    global CountGooglyFound
    print("Image found at the following locations:")
    print(locations)
    pyautogui.click(500, 500)
    CountGooglyFound += 1
    print(CountGooglyFound)

def handle_image_not_found():
    print("Image not found in the screenshot.")
    pyautogui.click(500, 50)

def main():
    global CountGooglyFound
    screenshot = take_screenshot()
    image_path = r'C:\Users\Iris\Desktop\ImageTest\Googly.png'
    found, locations = search_for_image(image_path, screenshot)
    
    if found:
        handle_image_found(locations)
        return  # 提前返回,避免后续逻辑
    
    # 这里可以添加更多条件判断,无需嵌套
    # 示例:添加额外条件,判断CountGooglyFound是否大于某个值
    if CountGooglyFound > 3:
        print("已找到多次目标图像")
        pyautogui.click(100, 100)
        return
    
    handle_image_not_found()

if __name__ == "__main__":
    main()
    # 若需在main执行后执行点击和打印,取消下方注释
    # pyautogui.click(50, 500)
    # print(CountGooglyFound)

内容的提问来源于stack exchange,提问作者Python Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 09:01:38