Python if-else 語句



Python if else 語句

Python 中,if-else 語句用於在if 語句中的條件為真時執行一段程式碼,而在條件為假時執行另一段程式碼。

if-else 語句的語法

Python 中 if-else 語句的語法如下:

if boolean_expression:
  # code block to be executed
  # when boolean_expression is true
else:
  # code block to be executed
  # when boolean_expression is false

如果布林表示式計算結果為 TRUE,則將執行if 塊內的語句;否則,將執行else 塊內的語句。

if-else 語句的流程圖

此流程圖顯示瞭如何使用 if-else 語句:

ifelse syntax

如果expr 為 True,則執行 stmt1、2、3 塊,然後預設流程繼續執行 stmt7。但是,如果expr 為 False,則執行 stmt4、5、6 塊,然後繼續預設流程。

上述流程圖的 Python 實現如下:

if expr==True:
   stmt1
   stmt2
   stmt3
else:
   stmt4
   stmt5
   stmt6
Stmt7

Python if-else 語句示例

讓我們透過以下示例瞭解 if-else 語句的用法。在此,變數 age 可以取不同的值。如果表示式 age > 18 為真,則將顯示 有投票資格 訊息;否則,將顯示 無投票資格 訊息。下面的流程圖說明了此邏輯:

if-else

現在,讓我們看看上述流程圖的 Python 實現。

age=25
print ("age: ", age)
if age >=18:
   print ("eligible to vote")
else:
   print ("not eligible to vote")

執行此程式碼後,您將獲得以下輸出

age: 25
eligible to vote

要測試else 塊,請將age 更改為 12,然後再次執行程式碼。

age: 12
not eligible to vote

Python if elif else 語句

if elif else 語句允許您檢查多個表示式的真假,並在其中一個條件計算結果為 TRUE 時執行一段程式碼。

else 塊類似,elif 塊也是可選的。但是,程式只能包含一個else 塊,而可以在if 塊之後包含任意數量的elif 塊

Python if elif else 語句的語法

if expression1:
   statement(s)
elif expression2:
   statement(s)
elif expression3:
   statement(s)
else:
   statement(s)

if elif else 如何工作?

關鍵字elifelse if的簡寫形式。它允許邏輯以elif語句的級聯方式排列在第一個if語句之後。如果第一個if語句計算結果為假,則後續的elif語句將逐個評估,如果任何一個語句滿足條件,則退出級聯。

級聯中的最後一個是else塊,當所有前面的if/elif條件都失敗時,它將被執行。

示例

假設購買商品有不同的折扣額度:

  • 金額超過10000元,折扣20%;

  • 金額在5000-10000元之間,折扣10%;

  • 金額在1000-5000元之間,折扣5%;

  • 金額小於1000元,無折扣。

下圖是這些條件的流程圖。(此處應插入流程圖)

if-elif

我們可以使用if-else語句編寫上述邏輯的Python程式碼:

amount = 2500
print('Amount = ',amount)
if amount > 10000:
   discount = amount * 20 / 100
else:
   if amount > 5000:
      discount = amount * 10 / 100
   else:
      if amount > 1000:
         discount = amount * 5 / 100
      else:
         discount = 0

print('Payable amount = ',amount - discount)

設定amount變數來測試所有可能的條件:800、2500、7500和15000。輸出將相應變化。

Amount: 800
Payable amount = 800
Amount: 2500
Payable amount = 2375.0
Amount: 7500
Payable amount = 6750.0
Amount: 15000
Payable amount = 12000.0

雖然這段程式碼可以完美執行,但是如果仔細觀察每個if和else語句遞增的縮排級別,如果還有更多條件,將會難以管理。

Python if elif else語句示例

elif語句使程式碼更易於閱讀和理解。以下是使用if elif else語句實現相同邏輯的Python程式碼:(此處應插入程式碼)

amount = 2500
print('Amount = ',amount)
if amount > 10000:
   discount = amount * 20 / 100
elif amount > 5000:
   discount = amount * 10 / 100
elif amount > 1000:
   discount = amount * 5 / 100
else:
   discount=0

print('Payable amount = ',amount - discount)

上述程式碼的輸出如下:(此處應插入輸出)

Amount: 2500
Payable amount = 2375.0
廣告