9.8每日总结

match...case

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

match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。

语法格式如下:

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

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

实例


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"

mystatus=400
print(http_error(400))

以上是一个输出 HTTP 状态码的实例,输出结果为:

Bad request

一个 case 也可以设置多个匹配条件,条件使用 | 隔开,例如:

...
    case 401|403|404:
        return "Not allowed"
posted @ 2023-09-08 20:44  听着DJ读童话  阅读(12)  评论(0)    收藏  举报