Skip to content

Instantly share code, notes, and snippets.

@garrettdreyfus
Last active July 22, 2024 13:03
Show Gist options
  • Save garrettdreyfus/8153571 to your computer and use it in GitHub Desktop.
Save garrettdreyfus/8153571 to your computer and use it in GitHub Desktop.
Dead simple python function for getting a yes or no answer.
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 ")
@stacksjb
Copy link

stacksjb commented Sep 14, 2022

@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)

@matejkonopik
Copy link

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?"))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment