0

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?

MBee
  • 78
  • 7

2 Answers2

5

You can store these associations in a dictionary

weapons_roles = {
    "sword": "Knight",
    "katana": "Samurai",
    "axe": "Viking"
}
  1. Print something, whenever the key is not in the dict

    print(weapons_roles.get(weapon, "No role"))
    
  2. Print a role only if the weapon is known

    if weapon in weapons_roles:
        print(weapons_roles[weapon])
    
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
azro
  • 53,056
  • 7
  • 34
  • 70
  • 1
    This is the best answer since it handles the cases where the weapon might not exist in the dict – Chris Doyle Mar 19 '20 at 12:08
  • Slight nit: this prints something whether there is a match or not, while the original code only printed something if there was a match (i.e., there was no `else` clause). That can be handled by using a `try` statement to catch (and ignore) a `KeyError` raised by `weapons_roles[weapon]`. – chepner Mar 19 '20 at 12:13
  • @chepner or just with an if – azro Mar 19 '20 at 12:28
  • I might continue to use `get` with the `if` statement, to avoid repeating the lookup. `role = weapon_roles.get(weapon); if role is not None` or `if (role := weapon_roles.get(weapon)) is not None:`. This is even a slighter nit, though. – chepner Mar 19 '20 at 12:50
1

Try this below :

def example_function(weapon):
    weapon_dict = {'sword': 'Knight', 'katana': 'Samurai', 'axe': 'Viking'}
    return weapon_dict[weapon]
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8