一. 简介

前面一篇文章学习 python中的 if...elif if...else语句。文章如下:

python3中条件判断语句:if 语句与if嵌套语句-CSDN博客

本文继续来学习 python3中的条件判断语句,python3.10引入的 match...case条件判断语句。

二. python3中条件判断语句:match...case语句

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

case _: 类似于 C 和 Java 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。

1. 第一种语法格式

第一种语法格式如下:

match subject:
    case <pattern1>:
        do something_1
    case <pattern2>:
        do something_2
    case <pattern3>:
        do something_3
    case _:
        do something_default

下面来举例说明:

#!/usr/bin/env python3

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

print(http_error(404))

输出如下:

Not found

2. 第二种语法格式

第二中语法格式:可以使用 if 关键字在 case 中添加条件:

match expression:
    case pattern1:
        # 处理pattern1的逻辑
    case pattern2 if condition:
        # 处理pattern2并且满足condition的逻辑
    case _:
        # 处理其他情况的逻辑

下面是匹配元组的一个实例:

#!/usr/bin/env python3

def match_example(item):
    match item:
        case (x, y) if x == y:
            print(f"匹配到相等的元组: {item}")
        case (x, y):
            print(f"匹配到元组:{item}")
        case _:
            print("匹配到其他情况")
        
match_example((1, 1))
match_example((1, 3))

输出如下:

匹配到相等的元组: (1, 1)
匹配到元组:(1, 3)

关于 match...case语句暂时学习到这里。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐