match variable: #這里的variable是需要判斷的內(nèi)容
case ["quit"]:
statement_block_1 # 對應(yīng)案例的執(zhí)行代碼,當(dāng)variable="quit"時執(zhí)行statement_block_1 case ["go", direction]:
statement_block_2
case ["drop", *objects]:
statement_block_3
... # 其他的case語句
case _: #如果上面的case語句沒有命中,則執(zhí)行這個代碼塊,類似于Switch的default
statement_block_default
一個match語句的使用示例:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the Internet"
上述代碼等價于:
def http_error(status):
if status == 400:
return "Bad request"
elif status == 404:
return "Not found"
elif status == 418:
return "I'm a teapot"
else:
return "Something's wrong with the Internet"
age = int(input("Age of the dog: "))
print()
if age < 0:
print("This can hardly be true!")
elif age == 1:
print("about 14 human years")
elif age == 2:
print("about 22 human years")
elif age > 2:
human = 22 + (age -2)*5
print("Human years: ", human)
###
input('press Return>')
將以上腳本保存在 dog.py 文件中,并執(zhí)行該腳本:
python dog.py
Age of the dog: 1
about 14 human years
更多建議: