菜鸟教程《Python 3 教程》笔记(10):条件控制

笔记带有个人侧重点,不追求面面俱到。

10 条件控制

出处: 菜鸟教程 - Python3 条件控制

10.1 match…case

Python 3.10 增加了 match...case 的条件判断。match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。

语法:

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

10.1.1 基本模式匹配

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

10.1.2 序列模式匹配

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")

10.1.3 对象模式匹配

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")

10.1.4 OR 模式

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

10.1.5 守卫

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

扩展阅读:Python 3.10里面的Match-Case语法详解

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猎猫骑巨兽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值