Last active
November 18, 2024 11:01
-
-
Save garrettdreyfus/8153571 to your computer and use it in GitHub Desktop.
Dead simple python function for getting a yes or no answer.
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 yes_or_no(question): | |
reply = str(raw_input(question+' (y/n): ')).lower().strip() | |
if reply[0] == 'y': | |
return True | |
if reply[0] == 'n': | |
return False | |
else: | |
return yes_or_no("Uhhhh... please enter ") |
@willbelr, Thank you for this beautiful & elegant solution! I modified with casefold (in Python3) but am otherwise using as-is in a few scripts, and it works great!
def confirm_prompt(question: str) -> bool:
reply = None
while reply not in ("y", "n"):
reply = input(f"{question} (y/n): ").casefold()
return (reply == "y")
reply = confirm_prompt("Are you sure?")
print(reply)
My version using simple recursion:
def user_confirm(question: str) -> bool:
reply = str(input(question + ' (y/n): ')).lower().strip()
if reply[0] == 'y':
return True
elif reply[0] == 'n':
return False
else:
new_question = question
if "Please try again - " not in question:
new_question = f"Please try again - {question}"
return user_confirm(new_question)
if __name__ == "__main__":
print(user_confirm("Do you love me?"))
I prefer this approach:
def yes_or_no_prompt(question:str,default_yes=True)->bool:
inputMapping={
'y':'y',
"υ":'y',
"Υ":'y',
'n':'n',
'ν':'n',
'N':'n'
}
question = question.strip()
if question == "":
raise ValueError(f"Question is an empty string")
default ='n'
prompt_choice="(y/N)"
if default_yes:
default='y'
prompt_choice="(Y/n)"
reply = str(input(f"{question} {prompt_choice}: ")).lower().strip()
reply = reply[0] or default
reply = inputMapping[reply]
if reply not in ['y','n']:
raise ValueError(f'Invalid input for reply given {reply} instead of Y or N')
return reply=='y'
# Usage Example
if __name__ == "__main__":
while True:
try:
if yes_or_no_prompt("Are roses red?"):
print("Correct")
else:
print("Nope")
exit(0)
except ValueError:
print("I made a Boo Boo mommy")
The reason why is because I split whether I'll re-ask the question into another point whereas the value sanitization and checking is performed upon the function itself. Furthermore I set the default value as well. Furthermore I map any Greek Input given from user intop its respective English one in case keyboard layout is a non-English one.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How would I add an --yes or -y parser arg to @icamys solution?
first
parser.add_argument("--yes", "-y", help="Always accept")
and then what? :D sorry I am really new to python
maybe something like:
but that doesnt work