====== 第四章:条件语句 ======
===== 本章目标 =====
完成本章学习后,你将能够:
* 熟练使用if、elif、else进行条件判断
* 理解Python的真值判断机制
* 掌握match-case模式匹配(Python 3.10+)
* 编写清晰、高效的判断逻辑
===== if语句基础 =====
==== 基本语法 ====
# 简单if
age = 20
if age >= 18:
print("你已经成年")
# if-else
score = 75
if score >= 60:
print("及格")
else:
print("不及格")
# if-elif-else
temperature = 25
if temperature > 30:
print("炎热")
elif temperature > 20:
print("舒适") # 输出
elif temperature > 10:
print("凉爽")
else:
print("寒冷")
==== 多分支判断 ====
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
print(get_grade(85)) # B
===== 条件表达式详解 =====
==== 真值判断 ====
在条件语句中,以下值被视为**False**:
* None
* False
* 零值:0, 0.0, 0j
* 空序列:"", [], (), range(0)
* 空映射:{}
* 空集合:set()
其他所有值都被视为**True**。
# 检查列表是否为空
items = []
if items: # 等同于 if len(items) > 0
print("列表非空")
else:
print("列表为空") # 输出
# 检查字符串
name = ""
if name:
print(f"你好,{name}")
else:
print("请输入名字") # 输出
# 检查None
data = None
if data:
print("有数据")
else:
print("无数据") # 输出
==== 复合条件 ====
# 使用and/or
age = 25
income = 50000
if age >= 18 and income >= 30000:
print("符合贷款条件")
# 使用not
is_logged_in = False
if not is_logged_in:
print("请先登录")
# 复杂条件
user = {"name": "Alice", "age": 20, "verified": True}
if user.get("age", 0) >= 18 and user.get("verified"):
print("已认证成年用户")
==== 简化条件 ====
# 不推荐:与True/False比较
if is_valid == True: # 冗余
pass
# 推荐
if is_valid:
pass
# 不推荐:显式比较None
if x == None: # 应该用is
pass
# 推荐
if x is None:
pass
# 检查值是否在列表中
if x == 1 or x == 2 or x == 3:
pass
# 更简洁
if x in (1, 2, 3):
pass
===== 嵌套条件语句 =====
==== 基本嵌套 ====
is_member = True
purchase_amount = 150
if is_member:
if purchase_amount >= 100:
discount = 0.2
else:
discount = 0.1
else:
if purchase_amount >= 200:
discount = 0.1
else:
discount = 0
print(f"折扣: {discount * 100}%")
==== 重构嵌套(扁平化)====
# 上面的代码可以重构为更扁平的结构
if is_member and purchase_amount >= 100:
discount = 0.2
elif is_member:
discount = 0.1
elif purchase_amount >= 200:
discount = 0.1
else:
discount = 0
===== 模式匹配 match-case =====
Python 3.10+引入了**结构化模式匹配**(类似其他语言的switch-case但更强大):
==== 基本匹配 ====
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown Status"
print(http_status(404)) # Not Found
==== 或模式 ====
def get_day_type(day):
match day:
case "Saturday" | "Sunday":
return "周末"
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return "工作日"
case _:
return "无效日期"
==== 捕获值 ====
def describe_point(point):
match point:
case (0, 0):
return "原点"
case (x, 0):
return f"x轴上的点,x={x}"
case (0, y):
return f"y轴上的点,y={y}"
case (x, y):
return f"点 ({x}, {y})"
case _:
return "不是点"
print(describe_point((0, 0))) # 原点
print(describe_point((5, 0))) # x轴上的点,x=5
print(describe_point((3, 4))) # 点 (3, 4)
==== 匹配数据结构 ====
def handle_command(command):
match command:
case ["quit"]:
return "退出程序"
case ["load", filename]:
return f"加载文件: {filename}"
case ["save", filename, *options]:
return f"保存文件: {filename}, 选项: {options}"
case ["copy", src, dst]:
return f"复制 {src} 到 {dst}"
case {"type": "click", "x": x, "y": y}:
return f"点击位置: ({x}, {y})"
case {"type": "key", "key": key}:
return f"按下按键: {key}"
case _:
return "未知命令"
print(handle_command(["load", "data.txt"]))
print(handle_command(["save", "out.txt", "--force", "--backup"]))
print(handle_command({"type": "click", "x": 100, "y": 200}))
===== 条件语句最佳实践 =====
==== 1. 避免深层嵌套 ====
# 不好的代码(箭头代码)
def process_order_bad(order):
if order:
if order.is_valid():
if order.has_stock():
if order.payment_processed():
return order.ship()
else:
return "支付失败"
else:
return "库存不足"
else:
return "订单无效"
else:
return "无订单"
# 好的代码(提前返回)
def process_order_good(order):
if not order:
return "无订单"
if not order.is_valid():
return "订单无效"
if not order.has_stock():
return "库存不足"
if not order.payment_processed():
return "支付失败"
return order.ship()
==== 2. 使用卫语句 ====
def calculate_discount(price, is_member):
# 卫语句处理异常情况
if price < 0:
raise ValueError("价格不能为负")
if price == 0:
return 0
# 主逻辑
if is_member:
return price * 0.9
return price
==== 3. 适当使用策略模式 ====
# 用字典代替多个if-elif
def operation_add(a, b): return a + b
def operation_sub(a, b): return a - b
def operation_mul(a, b): return a * b
def operation_div(a, b): return a / b if b != 0 else float('inf')
operations = {
'+': operation_add,
'-': operation_sub,
'*': operation_mul,
'/': operation_div,
}
def calculate(a, b, op):
return operations.get(op, lambda a, b: None)(a, b)
===== 本章练习 =====
1. **BMI计算器**:根据身高体重计算BMI并输出健康状态
2. **闰年判断**:编写函数判断某年是否为闰年(四年一闰,百年不闰,四百年再闰)
3. **计算器**:使用match-case实现支持+、-、*、/的计算器
4. **成绩等级**:输入成绩,输出等级(A、B、C、D、F)及评价
5. **日期有效性**:判断输入的年月日是否构成有效日期
===== 本章小结 =====
本章我们学习了:
* if、elif、else的基本用法
* 真值判断机制
* 复合条件和条件简化
* Python 3.10+的match-case模式匹配
* 条件语句的最佳实践
下一章:[[python_course:chapter05|第五章:循环语句]]