从Python 3.10开始引入match语句,用于替代复杂的if-elif链,提升代码可读性。其语法为match变量后跟多个case分支,支持值匹配、结构解构与条件守卫。例如可匹配字符串命令或坐标元组,并通过通配符_处理默认情况。还能结合if条件判断状态码范围,适用于解析输入、处理API响应等场景。使用时需注意模式顺序,具体模式应优先于通用模式。

从Python 3.10版本开始,官方引入了
match
if-elif-else
match
match
基本语法如下:
match 变量:
case 模式1:
执行代码1
case 模式2:
执行代码2
case _:
默认操作
其中
_
立即学习“Python免费学习笔记(深入)”;
最简单的场景是匹配整数、字符串等固定值。比如,模拟一个命令行菜单:
command = "start"
match command:
case "start":
print("启动程序")
case "stop":
print("停止程序")
case "restart":
print("重启程序")
case _:
print("无效命令")
输出结果为:
启动程序
command
_
match
例如,处理坐标点:
point = (2, 5)
match point:
case (0, 0):
print("原点")
case (x, 0):
print(f"在X轴上,x={x}")
case (0, y):
print(f"在Y轴上,y={y}")
case (x, y):
print(f"普通点,坐标为({x}, {y})")
这段代码会输出:
普通点,坐标为(2, 5)
x
y
还可以添加条件判断,使用
if
status_code = 404
match status_code:
case code if code < 200:
print("信息响应")
case code if code < 300:
print("成功")
case code if code < 400:
print("重定向")
case code if code < 500:
print("客户端错误")
case code if code < 600:
print("服务器错误")
这适合处理连续范围的数值,逻辑清晰,避免冗长的if判断。
match
不过要注意,
match
基本上就这些。掌握
match
以上就是Pythonmatch函数入门教程初学者指南_match函数Python入门完整教学的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号