Created
March 14, 2017 19:39
-
-
Save marksharrison/730c097e198830ae08ce72ad2fe3a036 to your computer and use it in GitHub Desktop.
question_yes_no Function Python Snippet
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
import sys | |
def question_yes_no(question, default="yes"): | |
"""Asks yes/no question using input() function and returns the answer | |
Args: | |
str: "question" text presented to user | |
str: "default" the presumed answer if the user just hits <Enter> | |
Returns: | |
bool: "question_answer" is True for "yes" or False for "no" | |
""" | |
valid_answer = {"yes": True, "y": True, "ye": True, "no": False, "n": False} | |
if default is None: | |
prompt = " [y/n] " | |
elif default == "yes": | |
prompt = " [Y/n] " | |
elif default == "no": | |
prompt = " [y/N] " | |
else: | |
raise ValueError("Opps! Invalid default answer: '%s'" % default) | |
while True: | |
sys.stdout.write(question + prompt) | |
question_answer = input().lower() | |
if default is not None and question_answer == '': | |
return valid_answer[default] | |
elif question_answer in valid_answer: | |
return valid_answer[question_answer] | |
else: | |
sys.stdout.write("Opps! Please respond with 'yes' or 'no' (or 'y' or 'n')\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment