Skip to content

Instantly share code, notes, and snippets.

@wkettler
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkettler/9241283 to your computer and use it in GitHub Desktop.
Save wkettler/9241283 to your computer and use it in GitHub Desktop.
def prompt(question, answers):
"""
Prompt the user with a question and only accept defined answers.
Input:
question (str): Question string
answers (list): A list containing accpeted response value
Output:
answer (str|int): Provided answer
"""
print question
# Print a numbered list of answers
for i in range(len(answers)):
print ' %d. %s' % (i+1, answers[i])
while True:
choice = raw_input(">>> ")
try:
choice = int(choice)
answer = answers[choice-1]
# A ValueError is raised when a string is cast to an int
except ValueError:
print "Invalid input."
# An IndexError is raise when the list index is out of range
except IndexError:
print "Invalid input."
else:
# Lists can be indexed with negative numbers
if choice < 1:
print "Invalid input."
continue
break
return answer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment