扫码一下
查看教程更方便
可能会出现在条件解析为真后您想检查另一个条件的情况。在这种情况下,您可以使用嵌套的if 结构。在嵌套if结构中,你可以有一个,IF... ELIF ...ELSE 构造里面写另一个 IF... ELIF...ELSE 结构。
嵌套的if...elif...else构造的语法可能是
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
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