Python代码优化:避免嵌套if,满足条件时跳过后续代码回到while循环
问题与解决方案
业务背景
循环处理SQL表QUEUE_TEST中状态为Pending的Key,执行对应函数后将该Key的状态标记为Done。
示例表结构
Key Status A Pending B Pending C Pending
现有代码框架
def main(): try: cursor.execute("SELECT TOP 1 KEY FROM MODEL_FACTORY#PYTHON.QUEUE_TEST WHERE STATUS = 'Pending'") result = pd.DataFrame(cursor.fetchone()) while not result.empty: input_data = .... try: if conditionA == True: if conditionB == True: Test() if conditionC == True: if conditionD == False: # 后续业务逻辑 pass except Exception as e: # 异常处理 pass # 标记状态为Done的逻辑(原代码隐含步骤) # 重新获取下一个Pending Key的逻辑(原代码隐含步骤) except Exception as e: return
核心需求
当conditionB为True时,执行Test()后跳过当前循环内的所有后续代码(包括conditionC相关逻辑),直接回到while循环开头处理下一个Key,且避免使用嵌套if-else结构。
解决方案
使用Python的continue语句,在执行Test()后先完成当前Key的状态标记,再获取下一个待处理的Key,最后调用continue直接回到while循环开头,跳过当前循环的剩余代码。
修改后的关键代码片段:
def main(): try: # 初始化获取第一个Pending Key cursor.execute("SELECT TOP 1 KEY FROM MODEL_FACTORY#PYTHON.QUEUE_TEST WHERE STATUS = 'Pending'") result = pd.DataFrame(cursor.fetchone()) while not result.empty: current_key = result.iloc[0, 0] input_data = .... # 加载对应Key的数据 try: if conditionA: if conditionB: Test() # 执行目标函数 # 标记当前Key为Done cursor.execute("UPDATE MODEL_FACTORY#PYTHON.QUEUE_TEST SET STATUS = 'Done' WHERE KEY = ?", (current_key,)) # 获取下一个Pending Key cursor.execute("SELECT TOP 1 KEY FROM MODEL_FACTORY#PYTHON.QUEUE_TEST WHERE STATUS = 'Pending'") result = pd.DataFrame(cursor.fetchone()) # 跳过当前循环剩余代码,直接回到while开头 continue # 以下为conditionB为False时才会执行的逻辑 if conditionC: if not conditionD: # 后续业务逻辑 pass # conditionB为False时,完成状态标记 cursor.execute("UPDATE MODEL_FACTORY#PYTHON.QUEUE_TEST SET STATUS = 'Done' WHERE KEY = ?", (current_key,)) # 获取下一个Pending Key cursor.execute("SELECT TOP 1 KEY FROM MODEL_FACTORY#PYTHON.QUEUE_TEST WHERE STATUS = 'Pending'") result = pd.DataFrame(cursor.fetchone()) except Exception as e: # 异常处理:可根据需求添加日志、状态回滚等逻辑 print(f"处理Key {current_key}时出错: {str(e)}") # 异常情况下也需更新状态或重新获取下一个Key,避免死循环 cursor.execute("UPDATE MODEL_FACTORY#PYTHON.QUEUE_TEST SET STATUS = 'Error' WHERE KEY = ?", (current_key,)) cursor.execute("SELECT TOP 1 KEY FROM MODEL_FACTORY#PYTHON.QUEUE_TEST WHERE STATUS = 'Pending'") result = pd.DataFrame(cursor.fetchone()) except Exception as e: print(f"主流程出错: {str(e)}") return
说明
continue语句会直接终止当前循环的剩余代码执行,回到while循环的条件判断处,完美契合需求中“跳过后续代码回到循环开头”的要求。- 提前将状态标记和下一个Key的获取逻辑放在
continue之前,确保业务流程的完整性(执行函数后标记状态)。 - 避免了嵌套
if-else结构,让代码逻辑更清晰,后续新增逻辑时也无需调整嵌套层级。
内容的提问来源于stack exchange,提问作者PV8
相关产品推荐
相关产品推荐

