Python - 巢狀 if 語句



Python 支援巢狀 if 語句,這意味著我們可以在現有的if 語句中使用條件ifif...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 語句的流程圖:

nested if statement flowchart

巢狀 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....

帶有 else 條件的巢狀 if 語句

如前所述,我們可以在if 語句中巢狀if-else語句。如果if 條件為真,則將執行第一個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
廣告