Python 3 - 嵌套 IF 语句
-
简述
可能存在一种情况,当您想要在一个条件解析为真后检查另一个条件。在这种情况下,您可以使用嵌套if 构造。在一个嵌套的if构造,你可以有一个if...elif...else在另一个内部构建if...elif...else构造。 -
句法
嵌套的 if...elif...else 构造的语法可能是 -if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s) elif expression4: statement(s) else: statement(s)
-
例子
# !/usr/bin/python3 num = int(input("enter number")) 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")
-
输出
执行上述代码时,会产生以下结果 -enter number8 divisible by 2 not divisible by 3 enter number15 divisible by 3 not divisible by 2 enter number12 Divisible by 3 and 2 enter number5 not Divisible by 2 not divisible by 3