
在 3.10 版本之前,Python 從來沒有實現(xiàn) switch 語句在其他編程語言中所做的功能。
所以,如果你想執(zhí)行多個條件語句,你將不得不使用elif這樣的關(guān)鍵字:
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 實現(xiàn)了一個稱為“結(jié)構(gòu)模式匹配”的 switch case 特性。您可以使用match和case關(guān)鍵字來實現(xiàn)此功能。
有些人爭論是否match和casePython 中的關(guān)鍵字。如何在 Internet Explorer 中阻止某些網(wǎng)站這是因為您可以將它們都用作變量名和函數(shù)名。但那是另一回事了。
如果愿意,您可以將這兩個關(guān)鍵字都稱為“軟關(guān)鍵字”。
在本文中,我將向您展示如何使用matchandcase關(guān)鍵字在 Python 中編寫 switch 語句。
但在此之前,我必須向您展示 Python 程序員過去是如何模擬 switch 語句的。
Python 程序員如何模擬 Switch Case
過去,Pythonista 模擬 switch 語句有多種方式。
使用一個函數(shù),elif關(guān)鍵字就是其中之一,你可以這樣做:
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實現(xiàn) Switch 語句case在 Python 3.10 中
要編寫具有結(jié)構(gòu)模式匹配功能的 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與多語句和使用函數(shù)模擬 switch 語句相比,這是一種更簡潔的語法。
您可能注意到我沒有像在其他編程語言中那樣為每個案例添加 break 關(guān)鍵字。這就是 Python 的原生 switch 語句相對于其他語言的優(yōu)勢。break 關(guān)鍵字的功能是在幕后為您完成的。
結(jié)論
本文向您展示了如何使用“match”和“case”關(guān)鍵字編寫 switch 語句。您還了解了 Python 程序員在 3.10 版本之前是如何編寫它的。文章來源:http://www.zghlxwxcb.cn/news/detail-516769.html
Python match 和 case 語句的實現(xiàn)是為了提供其他編程語言(如 JavaScript、PHP、C++ 和其他語言)中的 switch 語句特性為我們提供的功能。文章來源地址http://www.zghlxwxcb.cn/news/detail-516769.html
到了這里,關(guān)于Python Switch 語句——Switch Case 示例的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!