Python3巢狀if語句

2019-10-16 23:10:47
可能有一種情況,當你想檢查另一個條件中的另一個條件解析為 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