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

python switch用法

作者:我在坚强也需要有人疼   发布日期:2026-04-28   浏览:54

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

def http_status(status):
    match status:
        case 200:
            return "OK"
        case 304:
            return "Not Modified"
        case 400:
            return "Bad Request"
        case 401:
            return "Unauthorized"
        case 403:
            return "Forbidden"
        case 404:
            return "Not Found"
        case _:
            return "Unknown Status"

# 示例调用
print(http_status(200))  # 输出: OK
print(http_status(404))  # 输出: Not Found
print(http_status(500))  # 输出: Unknown Status

解释说明:

  • match-case 是 Python 3.10 引入的新语法,类似于其他语言中的 switch-case
  • match 关键字后面跟的是要匹配的值(在这个例子中是 status)。
  • 每个 case 后面跟的是一个模式,如果匹配成功,则执行对应的代码块。
  • 最后一个 case _: 是默认情况,类似于 default,当没有匹配到任何情况时会执行这里的代码。

上一篇:python 获取当前路径

下一篇:python reduce

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

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

Laravel 中文站