Python 支持嵌套 if 语句,这意味着我们可以使用条件 if 和 if...else 语句。
在某些情况下,您可能希望在初始条件解析为 true 后检查其他条件。在这种情况下,你可以使用嵌套的 if 构造。
此外,在嵌套的 if 构造中,您可以包含一个 if...elif...else 结构中插入另一个 if...elif...else 结构。
嵌套 if 语句的语法
具有 else 条件的嵌套 if 构造的语法将如下所示 -
if boolean_expression1:
statement(s)
if boolean_expression2:
statement(s)
嵌套 if 语句流程图
以下是 Python 嵌套 if 语句的流程图 -

嵌套 if 语句示例
下面的示例显示了嵌套 if 语句的工作原理 -
num = 36
print ("num = ", num)
if num % 2 == 0:
if num % 3 == 0:
print ("Divisible by 3 and 2")
print("....execution ends....")
当您运行上述代码时,它将显示以下结果 -
num = 36
Divisible by 3 and 2
....execution ends....
Divisible by 3 and 2
....execution ends....
具有 else 条件的嵌套 if 语句
如前所述,我们可以将 if-else 语句嵌套在 if 语句中。如果 if 条件为 true,则将执行第一个 if-else 语句,否则将执行 else 块内的语句。
语法
具有 else 条件的嵌套 if 构造的语法将如下所示 -
if expression1:
statement(s)
if expression2:
statement(s)
else
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)
例
现在让我们用 Python 代码来了解它是如何工作的 -
num=8
print ("num = ",num)
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
执行上述代码时,它会生成以下输出 -
num = 8
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3