python:chapter04

第四章:条件语句

完成本章学习后,你将能够:

  • 熟练使用if、elif、else进行条件判断
  • 理解Python的真值判断机制
  • 掌握match-case模式匹配(Python 3.10+)
  • 编写清晰、高效的判断逻辑
# 简单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

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}))
# 不好的代码(箭头代码)
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()
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
# 用字典代替多个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/chapter04.txt
  • 最后更改: 2026/04/09 14:24
  • 张叶安