Is there a better way to map a user input to a list of possible replies than this function I cobbled together?

5 days ago 12
ARTICLE AD BOX

I have this function I came up with as a python noob that takes an "inputMap", a 2-dimensonal array as follows:

exampleInputMap = [ ['1', 'a', -1], # do the first action ['2', 'b'], # do the second action ['3', 'h'], # print help ['4', 'q'] # quit the program ] def mapInputToAction(inputMap, matchFirstCharOnly=True, prompt='> '): while True: response = input(prompt) if len(response) == 0: for index, row in enumerate(inputMap): if -1 in row: return index else: for index, row in enumerate(inputMap): if matchFirstCharOnly: if response[0] in row: return index else: if response in row: return index

This is used in a while loop, fed into a switch/case statement. It gets an input from the user each time, and then returns an integer that tells the switch/case what action to do each time. Is this a good way to accomplish this, or is there a better way to do this (perhaps with dictionaries)? I'm trying to build good coding habits by practicing, but I don't want practice bad techniques.

Read Entire Article