HW03 判斷敘述式

 1.Notebooklm

2.影片

3.學習卡

4.測驗








5.

  1. 多向條件分支(if、elif、else)

    • 說明:Python 使用 if 處理條件成立時的程式區塊,配合 elif 進行多條件的串聯檢查,若所有條件皆不成立時則執行 else。程式會「由上往下依序檢查」,第一個成立的條件執行後即跳過其餘分支。語法上,條件行尾必須加冒號 :,下方區塊須縮排(通常為 4 格);若暫不需執行動作,可用 pass 作為佔位符。
    • 範例:
      score = 75
      
      if score >= 90:
          print("優等")
      elif score >= 60:
          print("及格")
      else:
          print("不及格")
      
  2. 邏輯運算子與真假值規則(Truthy / Falsy)

    • 說明:條件式可搭配比較運算子(如 ==、>=)與邏輯運算子(and、or、not)組合複合判斷。此外,Python 支援任何資料型態的真假值自動判定:數字 0、0.0、空字串 ""、空容器([]、{}、())、None 與 False 都會被判定為假(False),其餘非零或非空值則視為真(True)。
    • 範例:
      age = 20
      has_ticket = True
      
      if age >= 18 and has_ticket:
          print("可以入場")
      else:
          print("不能入場")
      
  3. 簡化條件與多層判斷(三元運算式與巢狀判斷)

    • 說明:當判斷邏輯含有多層遞進關係時,可在 if 區塊內嵌套另一個判斷式(稱為巢狀判斷);若屬於簡單的二選一賦值,則可採用三元運算式簡化,語法為 變數 = 值1 if 條件式 else 值2。
    • 範例:
      age = 20
      status = "成年" if age >= 18 else "未成年"
      print(status)
6.115103127 %5+1 使用心得

程式核心邏輯說明

這段程式透過 input() 取得使用者輸入的「溫度 (temp)」與「濕度 (hum)」,並使用多層巢狀 if...else 結構與 and 邏輯運算子進行多重條件篩選,以決定對應的運動項目。


逐步執行流程分析(輸入 temp = 'cold' 且 hum = 'humid')

  1. 第一層 if 判斷:

    • 條件式:temp == 'warm' and hum == 'dry'
    • 比較過程:'cold' == 'warm'(結果為 False)。
    • 結果:邏輯 and 運算需要兩端條件皆為 True 才會成立,故此條件為 False。程式跳過 print('Play Basketball'),進入第一個 else 區塊。
  2. 第二層 if 判斷:

    • 條件式:temp == 'warm' and hum == 'humid'
    • 比較過程:'cold' == 'warm'(結果為 False)and 'humid' == 'humid'(結果為 True)。
    • 結果:第一個條件不成立,and 運算結果仍為 False。程式跳過 print('Play Tennis'),進入第二個 else 區塊。
  3. 第三層 if 判斷:

    • 條件式:temp == 'cold' and hum == 'dry'
    • 比較過程:'cold' == 'cold'(結果為 True)and 'humid' == 'dry'(結果為 False)。
    • 結果:雖然溫度符合,但濕度不符合,and 運算結果仍為 False。程式跳過 print('Play Cricket'),進入最內層的 else 區塊。
  4. 執行最終 else 區塊:

    • 結果:當所有前面的條件都不成立時,程式直接執行預設的 else 區塊,輸出最終結果 Swim。

程式結構觀念與重構建議

  • 巢狀判斷(Nested Conditions):將 if...else 內嵌在另一個 else 內稱為巢狀判斷。雖然邏輯正確,但層級過深會影響程式碼的可讀性。
  • 使用 elif 重構:Python 提供了 elif(else if)語法,可以將多個條件分支平行排列,使邏輯更直觀:
temp = input('Enter the temperature:(a) warm b) cold): ')
hum = input('Enter humidity: (a) humid b) dry): ')

if temp == 'warm' and hum == 'dry':
    print('Play Basketball')
elif temp == 'warm' and hum == 'humid':
    print('Play Tennis')
elif temp == 'cold' and hum == 'dry':
    print('Play Cricket')
else:
    print('Swim')









留言

這個網誌中的熱門文章

HW02 運算子表達式