Dealing with a KeyError in python3.x


#1

Let’s the user choose which topic they would like to complete and the difficulty they wish to complete this topic in.

It will display a range of questions about the topic the user has chosen to do based on the difficulty.

Once run, the two variables ‘options’ and difficulty’ will print out onto python, the topics and difficulty. Once given an input, the program displays a ‘KeyError’. For example when I input ‘a’ (arithmetic) and ‘e’ (easy) it will not display the questions for arithmetic but instead this KeyError. How would I overcome this KeyError?

options = input("Choose 'a' for arithmetic or 'c' for computing: ")
difficulty = input("Choose 'e' for easy , 'm' for medium , 'h' for hard: ")

mapping = {'a': {
   'e': "What is 4+4?",
   'm': "What is 8x8+4-2?",
   'h': "What is 8+4+3-2x8+2?"
}}

mapping2 = {'c': {
    'e': "What is code?",
    'm': "What is the IBM primarily used for?",
    'h': "State the differences between Binary and Hex values?"
}}

question = mapping[options][difficulty]
moreQuestion = mapping2[options][difficulty]
answer = int(input(question))

#2

you can’t do both here:


question = mapping[options][difficulty]
moreQuestion = mapping2[options][difficulty]

if the user enters a, mapping2['a'] will give a key error, giving mapping2 has no key a. same logic applies for mapping['c'], so the simple solution would be to use if, elif, else (you choice which are best)

the better solution would be to use try/except to catch any key errors, just to be safe. using if/elif/else combined with try except is possible

it might also be wise to verify user input, never trust user input!