Python Switch 语句——Switch Case 示例
 
 
   在 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 特性。您可以使用match和case关键字来实现此功能。
有些人争论是否match和casePython 中的关键字。如何在 Internet Explorer 中阻止某些网站这是因为您可以将它们都用作变量名和函数名。但那是另一回事了。
如果愿意,您可以将这两个关键字都称为“软关键字”。
在本文中,我将向您展示如何使用matchandcase关键字在 Python 中编写 switch 语句。
但在此之前,我必须向您展示 Python 程序员过去是如何模拟 switch 语句的。
Python 程序员如何模拟 Switch Case
过去,Pythonista 模拟 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
"""如何使用matchand实现 Switch 语句case在 Python 3.10 中
要编写具有结构模式匹配功能的 switch 语句,可以使用以下语法:
match term:
    case pattern-1:
         action-1
    case pattern-2:
         action-2
    case pattern-3:
         action-3
    case _:
        action-default请注意,下划线符号用于在 Python 中为 switch 语句定义默认情况。
下面显示了使用匹配大小写语法编写的 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 关键字的功能是在幕后为您完成的。
结论
本文向您展示了如何使用“match”和“case”关键字编写 switch 语句。您还了解了 Python 程序员在 3.10 版本之前是如何编写它的。
Python match 和 case 语句的实现是为了提供其他编程语言(如 JavaScript、PHP、C++ 和其他语言)中的 switch 语句特性为我们提供的功能。