Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python switch

作者:〖掉望   发布日期:2026-07-19   浏览:21

# Python 3.10 引入了 match-case 语法,可以实现类似 switch 的功能

def http_status_code(status):
    match status:
        case 200:
            return "OK"
        case 301 | 302:
            return "Redirect"
        case 400:
            return "Bad Request"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:
            return "Unknown Status Code"

# 示例调用
print(http_status_code(200))  # 输出: OK
print(http_status_code(404))  # 输出: Not Found
print(http_status_code(999))  # 输出: Unknown Status Code

解释说明:

  • match-case 是 Python 3.10 引入的新语法,类似于其他语言中的 switch-case
  • match 后面跟着要匹配的值,case 后面跟着匹配的模式和对应的代码块。
  • 可以使用 | 来表示多个值的匹配(如 301 | 302)。
  • _ 是默认情况,类似于 default,当没有匹配到任何情况时执行。

上一篇:python 全局变量

下一篇:python 随机数

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

python集合中的元素可以是列表

staticmethod在python中有

python 保存json文件

python的assert基本用法

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站