在case的标量,也可以是多值,多值之间通过|分割(与C、JAVA的switch-case不同),例如: ... case 401|403|404: return "Not allowed" match-case只有OR模式,没有AND模式 匹配枚举 可以通过定义枚举值来进行条件匹配,match-case看上去是把枚举值当做标量来处理。 class Color(): RED
case _: # 默认执行代码块 value 是要匹配的值。 case pattern 用于定义匹配的模式。 _ 是通配符,用于匹配所有未被前面模式匹配的情况,类似于 default。 示例 1. 简单的模式匹配 python status = 404 match status: case 200: print("OK") case 404: print("Not Found") case _: print("Unknown status"...
事实上,对于这个特定的例子,match-case 没有比 if-else 语法带来任何好处,如下所示。 def http_error(status): if status == 400: return "Bad request" elif status == 401: return "Unauthorized" elif status == 403: return "Forbidden" elif status == 404: return "Not found" else: return "Unk...
此外,这种方法还具有很好的扩展性,可以根据需要轻松地添加更多的条件分支。 4. 方案2:match-case 语句 从Python 3.10开始,Python引入了一种新的结构:match-case语句,它类似于其他编程语言中的switch语句。我们可以使用match-case语句来实现优雅的条件分支。 使用match-case语句,我们可以将前面的示例重写为: 代码语言:...
match-case 语句使用 match 关键字初始化并获取一个参数,然后使用 case 关键字与参数匹配。“_”是通配符,当没有任何匹配项时运行。match-case 实例:day=input("请输入一个数字(1 - 7):")match day: case "1": print("星期一") case "2": print("星期二") case "3": print...
今天分享Python高级编程之:深入解析Python中switch case的使用方法。 1、有什么用? 当代码中遇到很多条件判断的时候,如下代码所示,在没有match case之前,我们通常是通过if else做匹配的。 代码语言:python 代码运行次数:0 defselect_platform(name):ifname=="小破站":print(f"程序员晚枫的{name}账号名称是:程序员...
case _: print("Not a point") 对象模式匹配 class Point: def __init__(self, x, y): self.x = x self.y = y p = Point(0, 3) match p: case Point(x=0, y=y): print(f"Point is on the Y axis at {y}") case Point(x=x, y=0): ...
case _:print("Not a point") OR模式 设置多个匹配条件,条件使用| 隔开。 x = 2match x: case1 | 2 | 3:print("x is 1, 2, or 3") case _:print("x is something else") case 401|403|404:return"Not allowed" 守卫模式 使用if 在模式匹配中添加额外的条件。
match value: case 1: print("匹配到值为1") case 2: print("匹配到值为2") case _: print("匹配到其他值") match_example(1) # 输出: 匹配到值为1 match_example(2) # 输出: 匹配到值为2 match_example(3) # 输出: 匹配到其他值以上...
捕获变量:在模式中使用的变量会绑定到对应的值上,这些变量可以在该 case 块中使用。 类型提示:虽然 match 和case 本身不进行类型检查,但可以通过类型提示与 isinstance() 结合使用来进行更复杂的类型匹配。 通过使用 match 和case 语句,Python 提供了一种强大的工具来处理复杂的条件逻辑,使代码更加清晰和易于维护。