0
Python: What Try Error should I use?
Hi, I'm trying to build a dictionary, it seems like NameError is not the one to be used. What Except Error should I be using? ClinicalTerms={ "ICH":"International Community of Harmonization", "AE":"Adverse Event", "SAE":"Severe Adverse Event", } try: print(ClinicalTerms[input("Enter your abbreviation: ")]) except NameError as err : print(err + " is not in the dictionary")
3 Réponses
+ 2
Do you by any means need an error? (Then the natural error happening when the searched-for key is not in the dict is KeyError.)
Because there's also the get-method:
your_dict.get(key, whatever_you_want_instead)
Default for the 2nd arg is None, but you can define any sort of object you get returned in case the key isn't in that dict.
+ 3
Btw, your own code has the answer. Just enter any key that's not in the dictionary and see what kind of exception you get
+ 1
HonFu, thanks for the useful feedback. Both method worked nicely.