Python中没有内置的switch语句,但可以使用字典来实现类似的功能。以下是一个示例:
def switch_case(argument):
switcher = {
1: "Case 1",
2: "Case 2",
3: "Case 3",
4: "Case 4",
}
return switcher.get(argument, "Invalid case")
# 测试
print(switch_case(1)) # 输出:Case 1
print(switch_case(5)) # 输出:Invalid case
在上面的示例中,switch_case
函数接收一个参数argument
,并在switcher
字典中查找与其匹配的值并返回,如果找不到则返回默认值"Invalid case"。通过这种方式,可以实现类似于switch语句的功能。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:python中switch的用法是什么