I heard several times that coding like this is suboptimal:
if weapon == "sword":
print("Knight")
elif weapon == "katana":
print("Samurai")
elif weapon == "axe":
print("Viking")
How do I write such code optimally?
I heard several times that coding like this is suboptimal:
if weapon == "sword":
print("Knight")
elif weapon == "katana":
print("Samurai")
elif weapon == "axe":
print("Viking")
How do I write such code optimally?
You can store these associations in a dictionary
weapons_roles = {
"sword": "Knight",
"katana": "Samurai",
"axe": "Viking"
}
Print something, whenever the key is not in the dict
print(weapons_roles.get(weapon, "No role"))
Print a role only if the weapon is known
if weapon in weapons_roles:
print(weapons_roles[weapon])
Try this below :
def example_function(weapon):
weapon_dict = {'sword': 'Knight', 'katana': 'Samurai', 'axe': 'Viking'}
return weapon_dict[weapon]