You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python match语句语法报错求助:为何示例代码无法运行?

Python 3.11+ 可正常运行的match语句示例及常见错误排查

基础可运行示例

以下是不同场景下的标准match语句实现,均可直接在Python 3.11及以上版本运行:

1. 字面量匹配

def greet(day):
    match day:
        case "Monday":
            return "周一快乐,打起精神!"
        case "Friday":
            return "周五啦,准备周末!"
        case _:
            return "普通的一天,加油!"

print(greet("Monday"))  # 输出:周一快乐,打起精神!
print(greet("Sunday"))  # 输出:普通的一天,加油!

2. 带守卫条件的匹配

def check_number(num):
    match num:
        case x if x > 10:
            return f"{x} 大于10"
        case x if x == 10:
            return f"{x} 等于10"
        case x if x < 10:
            return f"{x} 小于10"

print(check_number(15))  # 输出:15 大于10
print(check_number(5))   # 输出:5 小于10

3. 序列类型匹配(列表/元组)

def process_sequence(seq):
    match seq:
        case [a, b, c]:
            return f"三个元素:{a}, {b}, {c}"
        case [a, *rest]:
            return f"第一个元素{a},剩余元素:{rest}"
        case (a, b):
            return f"二元组:{a}和{b}"

print(process_sequence([1,2,3]))    # 输出:三个元素:1, 2, 3
print(process_sequence([4,5,6,7]))  # 输出:第一个元素4,剩余元素:[5, 6, 7]
print(process_sequence((8,9)))      # 输出:二元组:8和9

4. 字典匹配

def process_user(user):
    match user:
        case {"name": name, "age": age} if age >= 18:
            return f"成年用户:{name},{age}岁"
        case {"name": name}:
            return f"用户:{name},年龄未提供或未成年"

print(process_user({"name": "张三", "age": 20}))  # 输出:成年用户:张三,20岁
print(process_user({"name": "李四"}))            # 输出:用户:李四,年龄未提供或未成年

常见语法错误排查点

  • 缩进错误:case分支必须严格缩进在match语句块内,遵循Python通用缩进规则
  • 遗漏冒号:每个case分支结尾必须添加冒号:,和if/for语句要求一致
  • 通配符写法错误:通配符_需单独作为case,不能附加变量名,正确写法为case _:
  • 守卫条件关键字错误:必须用if定义守卫条件,不可使用其他语言的when关键字

内容的提问来源于stack exchange,提问作者Cody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:02:57