Last active
August 29, 2015 13:56
-
-
Save wkettler/9241283 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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