📌 第 2 小時:條件判斷(if-elif-else)
在 Python 中,條件判斷使用 if-elif-else
,用來根據不同的條件執行不同的程式區塊。例如,當使用者輸入考試分數時,我們可以根據數值顯示不同的等級:
score = int(input("請輸入分數: "))
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("不及格")
🔹 語法規則
- 條件語法必須以
:
結尾 - 程式區塊使用縮排(Indentation)來區分(通常為 4 個空格)
elif
(else if 的縮寫)用於多重條件判斷else
用於處理所有不符合條件的情況(可省略)
🔹 比較運算符(Comparison Operators)
Python 中的 比較運算符 用來進行條件比較,結果為 True
或 False
:
運算符 | 說明 | 範例 | 結果 |
---|---|---|---|
== | 等於 | 5 == 5 | True |
!= | 不等於 | 5 != 3 | True |
> | 大於 | 5 > 3 | True |
< | 小於 | 5 < 3 | False |
>= | 大於等於 | 5 >= 5 | True |
<= | 小於等於 | 5 <= 3 | False |
範例:數字比較
x = 10
y = 5
if x > y:
print("x 大於 y")
範例:字串比較(按照字母順序)
if "apple" > "banana":
print("apple 比 banana 大")
else:
print("apple 比 banana 小")
🔹 字串比較時,Python 依據 ASCII 碼(A=65, B=66)進行比較,所以
"apple" < "banana"
為True
。
🔹 邏輯運算符(Logical Operators)
Python 允許使用 邏輯運算符 來組合多個條件:
運算符 | 說明 | 範例 |
---|---|---|
and | 且(兩個條件都要為 True) | x > 5 and x < 10 |
or | 或(只要一個條件為 True) | x > 5 or x < 3 |
not | 非(反轉條件) | not (x > 5) |
範例:使用 and
(且)
age = int(input("請輸入年齡: "))
if age >= 18 and age <= 65:
print("適合工作的年齡")
🔹 只有
age
介於 18 和 65 之間(包含 18、65),條件才會成立。
範例:使用 or
(或)
is_student = True
is_teacher = False
if is_student or is_teacher:
print("可以進入校園")
🔹 只要
is_student
或is_teacher
其中一個為True
,條件就成立。
範例:使用 not
(非)
has_ticket = False
if not has_ticket:
print("不能進入")
🔹
not
會反轉布林值,所以not False
變成True
,因此會執行print("不能進入")
。
🔹 巢狀條件判斷(Nested If)
當我們需要在條件內 再加入條件 時,可以使用 巢狀 if
:
age = int(input("請輸入年齡: "))
if age >= 18:
print("你已成年")
if age >= 65:
print("你已達退休年齡")
else:
print("你仍需工作")
else:
print("你還未成年")
🔹 說明
- 若
age >= 18
,則會執行print("你已成年")
- 若
age >= 65
,則會印出"你已達退休年齡"
- 否則,則會印出
"你仍需工作"
🔹 一行條件判斷(三元運算子)
Python 允許用 一行寫出 if-else 條件判斷,這稱為 三元運算子(Ternary Operator):
age = int(input("請輸入年齡: "))
message = "成年" if age >= 18 else "未成年"
print(message)
🔹 說明
if 條件 成立時的值 else 不成立時的值
- 當
age >= 18
,message = "成年"
,否則message = "未成年"
🔹 match-case
(Python 3.10+)
Python 3.10 之後支援 match-case
,類似 switch-case
:
grade = input("請輸入等級 (A, B, C, D): ")
match grade:
case "A":
print("優秀")
case "B":
print("良好")
case "C":
print("普通")
case "D":
print("不及格")
case _:
print("輸入錯誤")
🔹 說明
case
用來比對不同的情況,_
代表其他未匹配的情況。
📌 第 2 小時小結
✅ Python 使用 if-elif-else
來進行條件判斷
✅ 條件語法必須以 :
結尾,且使用縮排來表示區塊
✅ 比較運算符:==, !=, >, <, >=, <=
✅ 邏輯運算符:and, or, not
可用於組合多條件
✅ 巢狀 if
可以在條件內再加入條件
✅ 三元運算子讓 if-else
簡化成一行
✅ Python 3.10+ 支援 match-case
來取代 if-elif-else
學完這一章,你應該已經掌握 條件判斷的基本概念與應用,接下來可以學習 迴圈(for, while)!🚀
沒有留言:
張貼留言