流程控制#
流程控制決定程式執行的走向。Python 使用 if/elif/else 做條件判斷,搭配比較運算符、邏輯運算符與三元運算式,能以簡潔的語法處理各種分支情境。
if / elif / else#
Python 使用 if、elif、else 來做條件判斷,注意 縮排 是必要的:
1
2
3
4
5
6
7
8
| age = 20
if age < 18:
print("未成年")
elif age < 65:
print("成人")
else:
print("長者")
|
多個條件#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"成績等級:{grade}") # 成績等級:B
|
比較運算符#
| 運算符 | 說明 | 範例 |
|---|
== | 等於 | 5 == 5 → True |
!= | 不等於 | 5 != 3 → True |
> | 大於 | 5 > 3 → True |
< | 小於 | 5 < 3 → False |
>= | 大於等於 | 5 >= 5 → True |
<= | 小於等於 | 3 <= 5 → True |
邏輯運算符#
and(且)#
兩個條件都要為 True,結果才是 True:
1
2
3
4
5
| age = 25
has_license = True
if age >= 18 and has_license:
print("可以開車")
|
or(或)#
至少一個條件為 True,結果就是 True:
1
2
3
4
5
| is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("今天可以休假")
|
not(非)#
反轉布林值:
1
2
3
4
| is_raining = False
if not is_raining:
print("適合出門")
|
組合條件#
1
2
3
4
5
6
| temperature = 28
is_sunny = True
has_umbrella = False
if temperature > 25 and is_sunny and not has_umbrella:
print("天氣熱又晴朗,但沒帶傘,注意防曬")
|
成員運算符:in 與 not in#
1
2
3
4
5
6
7
8
9
10
11
12
| fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("有香蕉")
if "mango" not in fruits:
print("沒有芒果")
# 也可用在字串
email = "user@example.com"
if "@" in email:
print("格式正確")
|
身分運算符:is 與 is not#
is 比較的是 物件是否為同一個 (記憶體位置),而 == 比較的是 值是否相等 :
1
2
3
4
5
6
7
| # 檢查是否為 None 時,慣例用 is
result = None
if result is None:
print("尚無結果")
# 不要用 == 來比較 None
# if result == None: # 有效但不建議
|
三元運算式(條件運算式)#
Python 的三元表達式語法為 值A if 條件 else 值B:
1
2
3
4
5
6
7
8
9
| age = 20
status = "成人" if age >= 18 else "未成年"
print(status) # 成人
# 等同於
if age >= 18:
status = "成人"
else:
status = "未成年"
|
實際應用:
1
2
3
4
5
6
7
| score = 75
result = "及格" if score >= 60 else "不及格"
print(result) # 及格
# 也可以用在 print 中
x = -5
print(f"x 的絕對值是 {x if x >= 0 else -x}") # x 的絕對值是 5
|
match 陳述式(Python 3.10+)#
Python 3.10 引入了 match,類似其他語言的 switch:
1
2
3
4
5
6
7
8
9
10
11
| command = "quit"
match command:
case "start":
print("程式啟動")
case "stop":
print("程式停止")
case "quit" | "exit":
print("離開程式")
case _:
print(f"未知指令:{command}")
|
實戰範例#
BMI 計算與分類#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| weight = 70 # 公斤
height = 1.75 # 公尺
bmi = weight / (height ** 2)
print(f"BMI:{bmi:.1f}")
if bmi < 18.5:
category = "過輕"
elif bmi < 24:
category = "正常"
elif bmi < 27:
category = "過重"
else:
category = "肥胖"
print(f"體重狀態:{category}")
|
簡單計算機#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| a = 10
b = 3
operator = "+"
if operator == "+":
result = a + b
elif operator == "-":
result = a - b
elif operator == "*":
result = a * b
elif operator == "/" and b != 0:
result = a / b
elif operator == "/" and b == 0:
result = "錯誤:除數不能為零"
else:
result = "未知運算符"
print(f"{a} {operator} {b} = {result}")
|
閏年判斷#
1
2
3
4
5
6
7
8
| year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
if is_leap:
print(f"{year} 年是閏年")
else:
print(f"{year} 年不是閏年")
|