在case的标量,也可以是多值,多值之间通过|分割(与C、JAVA的switch-case不同),例如: ... case 401|403|404: return "Not allowed" match-case只有OR模式,没有AND模式 匹配枚举 可以通过定义枚举值来进行条件匹配,match-case看上去是把枚举值当做标量来处理。 class Color(): RED = 1 GREEN = 2 BLUE =...
事实上,对于这个特定的例子,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...
match-case 语句使用 match 关键字初始化并获取一个参数,然后使用 case 关键字与参数匹配。“_”是通配符,当没有任何匹配项时运行。match-case 实例:day=input("请输入一个数字(1 - 7):")match day: case "1": print("星期一") case "2": print("星期二") case "3": print...
此外,这种方法还具有很好的扩展性,可以根据需要轻松地添加更多的条件分支。 4. 方案2:match-case 语句 从Python 3.10开始,Python引入了一种新的结构:match-case语句,它类似于其他编程语言中的switch语句。我们可以使用match-case语句来实现优雅的条件分支。 使用match-case语句,我们可以将前面的示例重写为: 代码语言:...
今天分享Python高级编程之:深入解析Python中switch case的使用方法。 1、有什么用? 当代码中遇到很多条件判断的时候,如下代码所示,在没有match case之前,我们通常是通过if else做匹配的。 代码语言:python 代码运行次数:0 defselect_platform(name):ifname=="小破站":print(f"程序员晚枫的{name}账号名称是:程序员...
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 在模式匹配中添加额外的条件。
case 401|403|404: return "Not allowed" 3 模式也可以是解包操作,用于绑定变量 # 主题表达式是一个(x, y)元组 match point: case (0, 0): print("Origin") case (0, y): print(f"Y={y}") case (x, 0): print(f"X={x}") case (x, y): ...
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): ...
Python在3.10.0版本中新增了match……case语句,它源自C语言中的switch……case语句,但具有更强大的使用方法。文中将对match……case语句的一些简单使用方法进行探索,首先给出了全部源代码,然后再对各个用法进行分析。 源代码 importsysdefbasic_usage(x):i=0match x:case1:i=1case2:i=2case3|4:i=3case _:...
match value: case 1: print("匹配到值为1") case 2: print("匹配到值为2") case _: print("匹配到其他值") match_example(1) # 输出: 匹配到值为1 match_example(2) # 输出: 匹配到值为2 match_example(3) # 输出: 匹配到其他值以上...