原文: Python Switch Statement – Switch Case Example

在 3.10 版本之前,Python 从来没有实现 switch 语句在其他编程语言中所做的功能。

所以,如果你想执行多个条件语句,你将不得不像这样使用 elif 关键字:

age = 120

if age > 90:
    print("You are too old to party, granny.")
elif age < 0:
    print("You're yet to be born")
elif age >= 18:
    print("You are allowed to party")
else: 
    "You're too young to party"

# Output: You are too old to party, granny.

从 3.10 版本开始,Python 实现了一个称为“结构模式匹配”的 switch case 功能。你可以使用 matchcase 关键字来实现此功能。

有些人争论 matchcase 是否是 Python 中的关键字。这是因为你可以将它们都用作变量和函数名称。但那是另一回事了。

如果你愿意,可以将这两个关键字称为“软关键字”。

在本文中,我将向你展示如何在 Python 中使用 matchcase 关键字编写 switch 语句。

但在此之前,我必须向你展示 Python 程序员过去是如何模拟 switch 语句的。

Python 程序员如何模拟 Switch Case

在当时,Python 程序员有多种模拟 switch 语句的方法。

使用函数和 elif 关键字就是其中之一,你可以这样做:

def switch(lang):
    if lang == "JavaScript":
        return "You can become a web developer."
    elif lang == "PHP":
        return "You can become a backend developer."
    elif lang == "Python":
        return "You can become a Data Scientist"
    elif lang == "Solidity":
        return "You can become a Blockchain developer."
    elif lang == "Java":
        return "You can become a mobile app developer"

print(switch("JavaScript"))   
print(switch("PHP"))   
print(switch("Java"))  

"""
Output: 
You can become a web developer.
You can become a backend developer.
You can become a mobile app developer
"""

如何在 Python 3.10 中使用 match 和 case 关键字实现 Switch 语句

要使用结构模式匹配功能编写 switch 语句,可以使用以下语法:

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

请注意,下划线符号是用于为 Python 中的 switch 语句定义默认情况的符号。

下面显示了一个使用 match case 语法编写的 switch 语句示例。这个程序可以打印你在学习各种编程语言时可以成为什么:

lang = input("What's the programming language you want to learn? ")

match lang:
    case "JavaScript":
        print("You can become a web developer.")

    case "Python":
        print("You can become a Data Scientist")

    case "PHP":
        print("You can become a backend developer")
    
    case "Solidity":
        print("You can become a Blockchain developer")

    case "Java":
        print("You can become a mobile app developer")
    case _:
        print("The language doesn't matter, what matters is solving problems.")

这比多个 elif 语句和用函数模拟 switch 语句要简洁得多。

你可能注意到我没有像在其他编程语言中那样为每种情况添加 break 关键字。这就是 Python 的原生 switch 语句相对于其他语言的优势,break 关键字的功能是在幕后为你完成的。

小结

本文向你展示了如何使用 matchcase 关键字编写 switch 语句。你还了解了 Python 程序员在 3.10 版本之前是如何编写它的。

Python matchcase 语句的实现是为了提供其他编程语言(如 JavaScript、PHP、C++ 等)中的 switch 语句特性为我们提供的功能。

感谢你阅读本文。