返回博客

10. 条件判断:if-elif-else 与 match-case

10. 条件判断:if-elif-else 与 match-case

第十篇:条件判断——if-elif-else 与 match-case 完全指南

前言

程序的价值在于能够根据不同情况做出不同决策。本文全面讲解 Python 的条件控制结构:从基础的 if-elif-else 语句,到 Python 3.10 引入的 match-case 模式匹配语法,涵盖各种条件表达式的写法、常见陷阱和实战技巧。

基础 if 语句

最简单的条件判断

age = 20
if age >= 18:
    print("成年人")
print("程序继续运行")  # 无条件执行

if-else 分支

temperature = 25
if temperature > 30:
    print("天气炎热,注意防暑")
else:
    print("温度适宜")

多层 elif

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

布尔表达式与真值测试

比较运算符

运算符 含义 示例
== 等于 x == 10
!= 不等于 x != 10
> 大于 x > 5
>= 大于等于 x >= 5
< 小于 x < 5
<= 小于等于 x <= 5

逻辑运算符

# and — 两个都为 True
is_adult = age >= 18
has_license = True
can_drive = is_adult and has_license

# or — 至少一个为 True
is_weekend = True
is_holiday = False
can_rest = is_weekend or is_holiday

# not — 取反
active = True
not_active = not active

短路求值

# and:第一个 False 就停止
print(False and expensive_operation())  # 右边不执行

# or:第一个 True 就停止
print(True or expensive_operation())    # 右边不执行

真值表

以下值为 False(伪值):

  • None
  • False
  • 数值 0, 0.0, 0j
  • 空序列/集合:"", [], (), {}, set()

其余全部视为 True。

in 和 not in 成员检查

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)     # True
print("grape" not in fruits) # True

# 适用于字符串
print("lo" in "Hello")       # True

# 适用于字典键
user = {"name": "小明", "age": 25}
print("name" in user)        # True

三目运算符(三元表达式)

# value_if_true if condition else value_if_false
status = "成年" if age >= 18 else "未成年"

# 嵌套三目
result = "优秀" if score >= 90 else ("及格" if score >= 60 else "不及格")

match-case:Python 3.10+ 的模式匹配

基本语法

command = "LIST"
match command:
    case "START":
        print("启动服务")
    case "STOP":
        print("停止服务")
    case "RESTART":
        print("重启服务")
    case "LIST":
        print("列出当前状态")
    case _:          # 通配符相当于 else
        print("未知命令")

字面量匹配

number = 42
match number:
    case 0:
        print("零")
    case 1:
        print("一")
    case _:  # 其他数字
        print("其他")

变量捕获

action = "GOTO 北京"
match action.split():
    case ["GOTO", destination]:
        print(f"前往 {destination}")
    case ["EXIT", code]:
        print(f"退出,代码 {code}")
    case _:
        print("未知指令")

或模式

response = "YES"
match response.upper():
    case "Y" | "YES" | "TRUE":
        print("确认")
    case "N" | "NO" | "FALSE":
        print("取消")
    case _:
        print("无效输入")

类模式

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(10, 20)
match p:
    case Point(x=0, y=0):
        print("原点")
    case Point(x=x_val, y=y_val) as pt:
        print(f"点坐标: x={x_val}, y={y_val}")

常见条件判断陷阱

陷阱一:用 = 代替 ==

# ❌ 错误:赋值不是比较
if x = 5:      # SyntaxError!
    print("等于 5")

# ✅ 正确
if x == 5:
    print("等于 5")

陷阱二:链式比较的正确性

# ✅ Python 支持数学意义上的链式比较
x = 5
print(0 < x < 10)   # True — 等价于 (0 < x) and (x < 10)

# 范围检查非常有用
score = 85
if 0 <= score <= 100:
    print("有效分数")

陷阱三:可变默认参数

# ❌ 不要用列表做默认参数
def append_item(item, target=[]):
    target.append(item)
    return target
append_item(1)   # [1]
append_item(2)   # [1, 2] ← 意外结果!

# ✅ 正确做法
def append_item(item, target=None):
    if target is None:
        target = []
    target.append(item)
    return target

陷阱四:浮点数比较

# ❌ 不要直接用 == 比较浮点数
a = 0.1 + 0.2
b = 0.3
print(a == b)  # False! 因为精度问题

# ✅ 使用容差比较
import math
print(math.isclose(a, b))  # True

实战示例

简易计算器

def calculator(num1, operator, num2):
    match operator:
        case "+": return num1 + num2
        case "-": return num1 - num2
        case "*" | "x": return num1 * num2
        case "/":
            return "错误:除数不能为零" if num2 == 0 else num1 / num2
        case "**": return num1 ** num2
        case "%":
            return "错误:除数不能为零" if num2 == 0 else num1 % num2
        case _:
            return f"未知操作符:{operator}"

数据验证管道

def validate_input(data):
    match data:
        case str():
            if not data.strip():
                return "错误:输入不能为空字符串"
        case int() | float():
            pass
        case _:
            return f"错误:不支持的数据类型 {type(data).__name__}"
    if isinstance(data, (int, float)):
        if data < 0 or data > 100:
            return "警告:数值不在 0-100 范围内"
    return None  # 无错误

总结

本文讲解了 Python 条件控制的核心知识:

  1. if-elif-else — 多层条件分支的标准写法
  2. 布尔表达式 — and/or/not 运算及短路求值
  3. 真值测试 — 哪些值被视为 False
  4. 三目运算符 — value_if_true if cond else value_if_false
  5. in/not in — 高效的成员检查
  6. match-case — Python 3.10+ 的模式匹配语法
  7. 常见陷阱 — 赋值误用、浮点数比较、可变默认参数等

下一篇文章将深入讲解循环结构:for、while、break/continue 以及 range() 函数的详细用法。


本文是 Python 教程系列的第十篇。