首页 > 解决方案 > 完成 IF 语句后,如何阻止代码继续进入特定部分?

问题描述

我有多个IF要执行的语句,但是一旦满足任何 IF 语句的逻辑,我希望代码跳过任何 IF` 语句中未包含的特定部分。

我该怎么做呢?

当前如何设置代码:

 if 1 in df.index:
        if df.col1.isnull()[1] or (df.col1[1]==''):
           [rest of the code]

 if 2 in df.index:
        if df.col1.isnull()[2] or (df.col1[2]==''):
           [rest of the code]

 if 3 in df.index:
        if df.col1.isnull()[3] or (df.col1[3]==''):
           [rest of the code]


[code I want to skip once any of the IF statements have been fulfilled]

[code I need to run regardless]

标签: pythonpython-3.xif-statement

解决方案


您可以使用 if, elif 构造来构建逻辑,但是正如您所提到的,您想要跳过/运行不属于任何 if 块的代码的特定部分,这取决于在任何 if 块内完成的某些情况然后您可以使用标志在 if 块内翻转其值。

flag = True;
if condition1:
  flag = False

if flag:
  code to be skipped

推荐阅读