为了账号安全,请及时绑定邮箱和手机立即绑定

如何避免 If 语句的墙壁?

如何避免 If 语句的墙壁?

鸿蒙传说 2022-09-06 17:27:46
我多次听说这样的编码是不理想的:if weapon == "sword": print("Knight") elif weapon == "katana": print("Samurai") elif weapon == "axe": print("Viking")如何以最佳方式编写此类代码?
查看完整描述

2 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

您可以将这些关联存储在字典中


weapons_roles = {

    "sword": "Knight",

    "katana": "Samurai",

    "axe": "Viking"

}

打印一些东西,只要钥匙不在字典中


print(weapons_roles.get(weapon, "No role"))

仅当武器已知时才打印角色


if weapon in weapons_roles:

    print(weapons_roles[weapon])


查看完整回答
反对 回复 2022-09-06
?
心有法竹

TA贡献1866条经验 获得超5个赞

试试下面这个:


def example_function(weapon):

    weapon_dict = {'sword': 'Knight', 'katana': 'Samurai', 'axe': 'Viking'}

    return weapon_dict[weapon]


查看完整回答
反对 回复 2022-09-06
  • 2 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号