Switch Case 语句

PythonBeginner
立即练习

介绍

在本实验中,我们将学习如何使用 Python 3.10 中引入的新特性——Python Switch Case 语句,也称为结构模式匹配(Structural Pattern Matching)。与传统的 if-elif-else 语句相比,Switch Case 语句能够以更简单、更易读的方式匹配模式。

学习目标

  • Switch Case 语句
  • if 语句

与 Python if 语句的对比

在深入探讨 Python Switch Case 语句的示例之前,我们先将其与传统的 if-elif-else 语句进行对比。

以下是一个匹配 HTTP 响应代码的示例:

response_code = 200

if response_code == 200:
    print("OK")
elif response_code == 404:
    print("404 Not Found")
elif response_code == 500:
    print("Internal Server Error")

我们可以使用 Python Switch Case 语句重写相同的示例:

response_code = 201

match response_code:
    case 200:
        print("OK")
    case 404:
        print("404 Not Found")
    case 500:
        print("Internal Server Error")

如你所见,与 if-elif-else 语句相比,Python Switch Case 语句更加简洁且易于阅读。

以下是 Switch Case 语句的语法:

match term:
    case pattern-1:
        action-1
    case pattern-2:
        action-2
    case pattern-3:
        action-3
    case _:
        action-default

其中,term 是你想要与模式匹配的值。模式可以是单个值、元组、列表、内置类,或者使用或运算符 (|) 组合这些模式。_ 是一个通配符模式,可以匹配任何值。

使用 or 模式进行匹配

在这个示例中,管道字符(|or)允许 Python 为两个或多个 case 返回相同的响应。

response_code = 502
match response_code:
    case 200 | 201:
        print("OK")
    case 500 | 502:
        print("Internal Server Error")

由于 response_code 的值为 500 或 502,因此会输出 "Internal Server Error"。

我们可以使用下划线符号 _ 来定义一个默认的 case。请看以下示例:

response_code = 800

match response_code:
    case 200 or 201:
        print("OK")
    case 500 or 502:
        print("Internal Server Error")
    case _:
        print("Invalid Code")

在这个示例中,由于 response_code 的值未被任何 case 覆盖,因此输出将是 "Invalid Code"。

匹配内置类

我们还可以基于内置类来匹配模式。请看以下示例:

response_code = ["300"]

match response_code:
    case int():
        print('response_code is a number')
    case str():
        print('response_code is a string')
    case list():
        print('response_code is a list')
    case _:
        print('response_code is a unknown type')

由于 response_code 是一个列表,因此会输出 "response_code is a list"。

总结

在本实验中,我们学习了如何使用 Python 3.10 中引入的 Python Switch Case 语句。我们将其与传统的 if-elif-else 语句进行了对比,并通过多个示例练习了匹配单个值、or 模式、可迭代对象的长度、默认 case 的下划线符号以及内置类。

希望你喜欢这个实验并学到了一些新知识!