如何将Bash脚本switch case语句转换为Python3的对应实现
Bash switch case 转 Python3 实现方案
Python 3.10 版本开始正式加入了原生的match/case语法,可以直接等价实现Bash里的case逻辑;如果是更低版本的Python3,可以用字典映射的方式实现相同效果。
方案1:Python 3.10+ 原生match/case 写法(和原Bash逻辑完全对齐)
这个写法最贴近原有Bash case的分支判断逻辑,直接逐行对应转换即可:
# 读取用户输入,等价于Bash的read class class_choice = int(input().strip()) # 初始化职业属性变量 class_type = "" hp = 0 attack = 0 magic = 0 # 等价Bash的case判断逻辑 match class_choice: case 1: class_type = "Samurai" hp = 10 attack = 11 magic = 12 case 2: class_type = "Warrior" hp = 13 attack = 4 magic = 12 case 3: class_type = "Ninja" hp = 30 attack = 4 magic = 16 # 可选默认分支,处理输入不合法的场景 case _: raise ValueError("请输入1、2、3范围内的有效职业编号") # 输出结果,等价于原Bash的echo逻辑 print(f"You chosen the {class_type} class. Your HP is {hp} and your attack is {attack} and your magic is {magic}.")
注意:Python中
class是定义类的保留关键字,不能直接作为变量名,因此将原Bash里的class变量重命名为class_choice避免语法错误。
方案2:兼容Python 3.10以下版本的字典映射写法
如果你的运行环境Python版本低于3.10,没有match/case语法,可以用Python社区传统的字典映射方式实现switch case效果,代码更简洁:
class_choice = int(input().strip()) # 所有分支的配置统一存在字典中,key对应case的匹配值 class_config = { 1: ("Samurai", 10, 11, 12), 2: ("Warrior", 13, 4, 12), 3: ("Ninja", 30, 4, 16) } if class_choice not in class_config: raise ValueError("请输入1、2、3范围内的有效职业编号") class_type, hp, attack, magic = class_config[class_choice] print(f"You chosen the {class_type} class. Your HP is {hp} and your attack is {attack} and your magic is {magic}.")
关键说明
- 原Bash的
read读取输入默认是字符串匹配,上述代码用int()转换输入是为了兼容用户输入带空格、换行的场景,如果要完全和Bash行为一致做字符串匹配,去掉int()转换,把case匹配值或者字典key改成字符串格式的"1"/"2"/"3"即可。 - 原Bash代码如果输入非1/2/3的值,后续echo调用变量会出现空值错误,上述两个方案都增加了合法值校验,避免出现未定义变量的问题。
内容的提问来源于stack exchange,提问作者Muhammad Mare'i
相关产品推荐
相关产品推荐

