MBe*_*Bee 0 python if-statement python-3.x
我多次听说这样的编码不是最理想的:
if weapon == "sword":
print("Knight")
elif weapon == "katana":
print("Samurai")
elif weapon == "axe":
print("Viking")
Run Code Online (Sandbox Code Playgroud)
如何以最佳方式编写此类代码?
您可以将这些关联存储在字典中
weapons_roles = {
"sword": "Knight",
"katana": "Samurai",
"axe": "Viking"
}
Run Code Online (Sandbox Code Playgroud)
每当密钥不在字典中时,打印一些内容
print(weapons_roles.get(weapon, "No role"))
Run Code Online (Sandbox Code Playgroud)Print a role only if the weapon is known
if weapon in weapons_roles:
print(weapons_roles[weapon])
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |