Python, can I make a single if statement rather than a dozen if drawing from a dictionary?
Question:
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!
Answers:
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")
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!
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")