-2

Using Python: Hello, I am wondering if I am able to make a single statement rather than a dozen if/elif statements. My dictionary has 12 weapons with key values from 1-12. I imagine there must be a way to make a statement similar to 'if selection is 1-12, then print "You have chosen [the correct dictionary value]. Below is my current first if statement:

weapons = {
        1: "Dagger",
        2: "Long Sword",
        3: "Bastard Sword"
    }
print("\nWhat type of weapon do you use?")
print("Please choose from the following:\n")
    for key, value in weapons.items():
        print(key, ":", value)
    try:
        selection = int(input("\nSelect a number: "))
        if selection == 1:
            print("You have chosen the " + weapons[1] + "\n")
            print("You have chosen, wisely.")

Thank you for your help!

fuzzbuzz
  • 3
  • 2
  • Your weapons and their IDs are stored in a dictionary. Think about how a dictionary is useful. How do you usually access _specific_ dictionary values? Then look at these two code snippets: `selection == 1` / `weapons[1]` - something is the same between them. What is it? – kalatabe Sep 28 '22 at 19:35
  • In fact, it appears you already know how to look up the value, because the code already does it: `weapons[1]`. So - what exactly is the difficulty? Why do you think the code should need multiple `if` statements? What *problem do you hope to solve* by having them? – Karl Knechtel Sep 28 '22 at 19:37

1 Answers1

1

You can test if selection is in the dictionary

if selection in weapons:
    ...

Or, since you have a try/except block anyway, catch the KeyError on failure. Here, using an f-string, python will attempt to get weapons[selection] and will raise KeyError if its not there. Similarly, on bad input that cannot be converted to int, python will raise ValueError. One try/except catches both errors.

try:
    selection = int(input("\nSelect a number: "))
    print(f"You have chosen the {weapons[selection]}")
    print("You have chosen, wisely.")
except (KeyErrror, ValueError):
    print(f"Selection '{selection}' is not valid") 
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Ah, you eventually came to the same conclusion as I did about *what the actual question is*. In this case, of course, it is a common duplicate. – Karl Knechtel Sep 28 '22 at 19:48
  • @KarlKnechtel - Considering the structure of the example, I thought it best answer the exact question (use `in`) but also highlight how one can leverage exception handling. Since this covers both the dictionary lookup and the `input` conversion, I think this answer is still valuable. – tdelaney Sep 28 '22 at 19:53