Skip to content

Instantly share code, notes, and snippets.

Created June 24, 2018 18:54
What would you like to do?
Compares a user's input to a list of allowable reponses and returns the keyword.
def parse_response(multiple_choice, prompt=None):
Splits a user's input into individual words and searches a list
of allowable responses for a unique match, then returns the word
that matches one of the options.
List comprehension syntax explained for my own reference:
1. for i in response.split() - breaks every word of response
into individual strings
2. if i in multiple_choice - searches for ALL recognized words
within list of possible keywords
3. [i for ...] - appends all intersections from the rest of the
list comprehension to a list
multiple_choice : list or dict
The options allowed within the user's response. If a dict
is passed, a list is generated from dict.keys().
prompt : string
If not specified, the prompt for user input prints a single
caret >. A string can be specified to print a more useful
prompt if need be.
The keyword from the input that matches allowable options.
if type(multiple_choice) is dict:
multiple_choice = multiple_choice.keys()
while True:
if prompt is None:
response = input('> ')
response = input('< ' + prompt + ' >\n').lower()
keywords = [i for i in response.split() if i in multiple_choice]
if len(keywords) != 1:
print('Sorry, that is not an option or it wasn\'t recognized.\n'
'Try one of the following:')
return keywords[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment