Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python, can I make a single if statement rather than a dozen if drawing from a dictionary?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

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") 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading