Python条件控制语句:if语句,match……case语句

发布时间 2023-08-30 20:34:24作者: limalove

通常情况下,程序总是按顺序执行的。但是对于一些复杂的情况下,需要根据不同的情况选择性地执行程序语句,这时需要使用流程控制语句。

 

分支结构:条件判断语句 if语句

循环结构:循环控制语句(限制循环次数,避免死循环)

                 for语句和while语句(当型,而不是直到型)

 

 

match...case

Python 3.10 增加了 match...case 的条件判断,不需要再使用一连串的 if-else 来判断了。

case _: "  _ "是一个特殊的“占位符”模式,用于匹配任何值(类似于 else)。类似于 C 和 Java 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _: 
        <action_wildcard>

 

match ... case 是 Python 3.10 中引入的一个新特性,也被称为“模式匹配”或“结构化匹配”。

1,基本模式匹配

2,序列模式匹配

3,对象模式匹配

4,OR模式匹配:设置多个匹配条件,条件使用 | 隔开。

5,守卫模式匹配:使用if语句。

 

基本模式匹配

x = 10
match x:
    case 10:
        print("x is 10")
    case 20:
        print("x is 20")
    case _:
        print("x is something else")

 

序列模式匹配

point = (2, 3)
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Point is on the Y axis at {y}")
    case (x, 0):
        print(f"Point is on the X axis at {x}")
    case (x, y):
        print(f"Point is at ({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):
        print(f"Point is on the X axis at {x}")
    case Point(x, y):
        print(f"Point is at ({x}, {y})")
    case _:
        print("Not a point")

 

OR模式

设置多个匹配条件,条件使用 | 隔开。

x = 2
match x:
    case 1 | 2 | 3:
        print("x is 1, 2, or 3")
    case _:
        print("x is something else")

 

    case 401|403|404:
        return "Not allowed"

 

守卫模式

使用 if 在模式匹配中添加额外的条件。

x = 10
match x:
    case x if x > 5:
        print("x is greater than 5")
    case _:
        print("x is 5 or less")