Python巢狀if語句

2019-10-16 23:08:00

當需要在條件求值為True後檢查其他條件時可能會出現情況。 在這種情況下,可以使用巢狀的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