As you mentioned, the easiest way is to use raw_input() (or simply input() for Python 3). There is no built-in way to do this. From Recipe 577058:

import sys


def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
            It must be "yes" (the default), "no" or None (meaning
            an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"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("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")

(For Python 2, use raw_input instead of input.) Usage example:

>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] [ENTER]
>>> True

>>> query_yes_no("Is cabbage yummier than cauliflower?", None)
Is cabbage yummier than cauliflower? [y/n] [ENTER]
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [y/n] y
>>> True
Answer from fmark on Stack Overflow
Top answer
1 of 16
286

As you mentioned, the easiest way is to use raw_input() (or simply input() for Python 3). There is no built-in way to do this. From Recipe 577058:

import sys


def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
            It must be "yes" (the default), "no" or None (meaning
            an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"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("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")

(For Python 2, use raw_input instead of input.) Usage example:

>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] [ENTER]
>>> True

>>> query_yes_no("Is cabbage yummier than cauliflower?", None)
Is cabbage yummier than cauliflower? [y/n] [ENTER]
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [y/n] y
>>> True
2 of 16
102

I'd do it this way:

# raw_input returns the empty string for "enter"
yes = {'yes','y', 'ye', ''}
no = {'no','n'}

choice = raw_input().lower()
if choice in yes:
   return True
elif choice in no:
   return False
else:
   sys.stdout.write("Please respond with 'yes' or 'no'")
🌐
Stack Abuse
stackabuse.com › bytes › handling-yes-no-user-input-in-python
Handling Yes/No User Input in Python
August 21, 2023 - (yes/no): ") if user_input.lower() in ["yes", "y"]: print("Continuing...") break elif user_input.lower() in ["no", "n"]: print("Exiting...") break else: print("Invalid input. Please enter yes/no.") In this code, we keep asking the user "Do you want to continue? (yes/no): " until they enter a valid response. If the response is "yes" or "y", we print "Continuing..." and break out of the loop.
Discussions

i dont know how to make a yes or no question in python and when i looked it up and used the code i found it didnt work
Just in case the OP doesn’t know, by adding .lower() to the answer it converts the input from the user to lowercase, so even if they have caps lock on it doesn’t matter. Also, as mentioned above, the code you are copying is missing sections where the hash are. You have to put your own action wherever they have said Do this/that, such as a print() More on reddit.com
🌐 r/learnpython
8
8
August 8, 2021
Using "if input" for a yes/no prompt
Seems like you've already gotten your answer, but I have a little suggestion. You should consider using enumerate() instead of creating your own counter variable. In other words, your code here: counter = 0 for row in reader: if len(row) > 0: if roll != row[2]: updated_data.append(row) counter += 1 else: student_found = True could be simplified into this: for counter, row in enumerate(reader): if len(row) >0: if roll != row[2]: updated_data.append(row) else: student_found = True enumerate() basically spits out your counter and your row, it just reduces the clutter. Also, based on the code you've presented, I'm not even sure why you're keeping a counter in the first place. It doesn't appear you're using it at all, so you could probably cut it out entirely. But if you're using it somewhere else in your code, enumerate() is handy. You should seriously look into the pandas library. You've gotta install it, but it's ridiculously powerful for data manipulation. Right now, your code generates two lists of students: one with the student you're trying to delete, and one without. This takes up a lot of memory, and it requires extra time to construct the latter list. Using pandas, you can use a boolean mask to simply eliminate the entry you want to remove. It accomplishes what you want, uses fewer lines of code, and substantially improves speed. Corey Schafer has a great series on the module , and I also highly highly highly recommend you check him out in general. Nobody I've encountered is remotely as good at demonstrating the use of various aspects of code in bare-bones, simple examples. His videos are getting a bit old, but they're 100% reliable for modern python, as far as I've seen. Seriously cannot recommend this guy enough if you're trying to learn. If you have any questions, feel free to shoot me a dm. I really like talking about this stuff, in case you couldn't tell from my wall of text answering questions you didn't ask in the first place lol More on reddit.com
🌐 r/learnpython
15
6
November 28, 2022
Newbie question - Programming help
I’m a master student at university. I’m woking on a minigame related to this. I have a task to program a ‘while loop’ that accepts input form the user that is supposed to work like this: If the user types “yes” the game starts, if the user types “no”, they gets a message saying ... More on discuss.python.org
🌐 discuss.python.org
9
0
October 21, 2022
Identify when python script is waiting for a manual input - Unix & Linux Stack Exchange
I'm writing a shell script which executes a Python script. The Python script halts for a manual enter to be provided. However, I don't want to have to press enter each time to the script. Instead, ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
🌐
GitHub
gist.github.com › garrettdreyfus › 8153571
Dead simple python function for getting a yes or no answer. · GitHub
Correct me if I am wrong but this might be OK with the Assigment Expressions (PEP 572) in Python 3.8 · while res:= input("Do you want to save? (Enter y/n)").lower() not in {"y", "n"}: pass ... def getch(): """Read single character from standard input without echo.""" import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch def yes_or_no(question): c = "" print(question + " (Y/N): ", end = "", flush = True) while c not in ("y", "n"): c = getch().lower() return c == 'y' if __name__ == "__main__": if not yes_or_no("Continue?"): print("NO") # ...or echo nothing and just provide newline os._exit(0) else: print("YES")
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-wait-time-wait-for-input
Python wait time, wait for user input | DigitalOcean
August 3, 2022 - Below short screen capture shows the complete program execution. Surprising, there is no easy way to wait for user input with a timeout or default value when empty user input is provided. I hope these useful features come in future Python releases.
🌐
Quora
quora.com › I’m-new-to-Python-how-can-I-write-a-yes-no-question
I’m new to Python, how can I write a yes/no question? - Quora
Normalize input with strip().lower() before checking. Accept common variants: "y", "yes", "n", "no" (optionally "yep", "nope"). Provide a clear prompt including accepted answers or a default. For scripts, prefer a helper function to centralize behavior and testing. This covers typical console, GUI and web patterns for asking yes/no questions in Python.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-input-yes-no
Yes/No question with user input in Python | bobbyhadz
If you have multiple words that you consider to be yes or no, add the words to a list and use the in operator to check for membership. ... Copied!yes_choices = ['yes', 'y'] no_choices = ['no', 'n'] while True: user_input = input('Do you want to continue?
🌐
EyeHunts
tutorial.eyehunts.com › home › while loop yes or no python | example code
While loop Yes or No Python | Example code
July 25, 2023 - Use while true with if statement and break statement to create a While loop yes or no in Python. Simple if while condition equal to “N” then wait for the user input of Y before exiting.
Find elsewhere
🌐
Medium
medium.com › @glasshost › yes-no-question-with-user-input-in-python-d74186c0e3ce
Guide: Yes/No question with user input in Python | by Glasshost | Medium
April 30, 2023 - `if answer == “yes”: print(“You entered ‘yes’.”) elif answer == “no”: print(“You entered ‘no’.”) else: print(“Invalid input. Please enter ‘yes’ or ‘no’.”)` Finally, we will run the code and test it out. If the user enters ‘yes’ or ‘no’, the program will confirm their answer. If the user enters anything else, the program will ask them to try again. In Python, asking for user input is easy with the `input()` function.
🌐
Reddit
reddit.com › r/learnpython › using "if input" for a yes/no prompt
r/learnpython on Reddit: Using "if input" for a yes/no prompt
November 28, 2022 -

In my record management program, if the user selects to delete a record of a student, I would like Python to display the Name of the specific student to confirm with the user "Y/N" that they would like to delete the record. Specifically it would look like:

        1. Create a new record.
        2. Show a record.
        3. Delete a record.
        4. Display All Records.
        5. Exit.

Enter your option [1 - 5]: 3
You have chosen "Delete a record."
Enter a Last Name: Ted
Are you sure you want to delete record with Last Name: Ted, First Name: Big? Enter Y or N.Y
Done! Press enter to continue.
returning to Main Menu.

I got the yes/no prompt down, Python confirms with the user whether or not they want to delete a record but it does not include the specific last name of the record to delete. How could I go about tweaking my code to include this? Here is my code for the Delete Record Module/function, I will also include the code for the main file.

Delete Record Function :

import csv
student_info = ['Student ID', 'First name', 'last name', 'age', 'address', 'phone number']
database = 'file_records.txt'


def delete_student():
    global student_info
    global database

    print("--- Delete Student ---")
    roll = input("Enter a Last Name: ")
    student_found = False
    updated_data = []
    with open(database, "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        counter = 0
        for row in reader:
            if len(row) > 0:
                if roll != row[2]:
                    updated_data.append(row)
                    counter += 1
                else:
                    student_found = True

    if student_found is True:

        if input("Are you sure you want to delete record (y/n) ") != "y":
            exit()
        with open(database, "w", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerows(updated_data)
        print("Student ", roll, "deleted successfully")
    else:
        print("Record not found")

    input("Press any key to continue")

Code for the main file/function:

from ShowAllRecords import show_record
from deleteRecord import delete_student
from showRecord import view_records
from createRecord import add_record
global student_info
global database

"""
Fields :- ['Student ID', 'First name', 'Last Name', 'age', 'address', 'phone number']
1. Create a new Record
2. Show a record
3. Delete a record
4. Display All Records.
5. Exit
"""


student_info = ['Student ID', 'First name', 'last name', 'age', 'address', 'phone number']
database = 'file_records.txt'


def display_menu():
    print("**********************************************")
    print("             RECORDS MANAGER    ")
    print("**********************************************")
    print("1. Create a new record. ")
    print("2. Show a record. ")
    print("3. Delete a record. ")
    print("4. Display All Records. ")
    print("5. Exit")


while True:
    display_menu()

    choice = input("Enter your choice [1-5]: ")
    if choice == '1':
        print('You have chosen "Create a new record."')
        add_record()
    elif choice == '2':
        print('You have chosen "Show a record"')
        show_record()
    elif choice == '3':
        print('You have chosen "Delete a record". ')
        delete_student()
    elif choice == '4':
        print('You have chosen "Display ALL records"')
        view_records()
    else:
        print('You have chosen to exit the program. Exiting...')
        break
Top answer
1 of 5
6
Seems like you've already gotten your answer, but I have a little suggestion. You should consider using enumerate() instead of creating your own counter variable. In other words, your code here: counter = 0 for row in reader: if len(row) > 0: if roll != row[2]: updated_data.append(row) counter += 1 else: student_found = True could be simplified into this: for counter, row in enumerate(reader): if len(row) >0: if roll != row[2]: updated_data.append(row) else: student_found = True enumerate() basically spits out your counter and your row, it just reduces the clutter. Also, based on the code you've presented, I'm not even sure why you're keeping a counter in the first place. It doesn't appear you're using it at all, so you could probably cut it out entirely. But if you're using it somewhere else in your code, enumerate() is handy. You should seriously look into the pandas library. You've gotta install it, but it's ridiculously powerful for data manipulation. Right now, your code generates two lists of students: one with the student you're trying to delete, and one without. This takes up a lot of memory, and it requires extra time to construct the latter list. Using pandas, you can use a boolean mask to simply eliminate the entry you want to remove. It accomplishes what you want, uses fewer lines of code, and substantially improves speed. Corey Schafer has a great series on the module , and I also highly highly highly recommend you check him out in general. Nobody I've encountered is remotely as good at demonstrating the use of various aspects of code in bare-bones, simple examples. His videos are getting a bit old, but they're 100% reliable for modern python, as far as I've seen. Seriously cannot recommend this guy enough if you're trying to learn. If you have any questions, feel free to shoot me a dm. I really like talking about this stuff, in case you couldn't tell from my wall of text answering questions you didn't ask in the first place lol
2 of 5
4
but it does not include the specific last name of the record to delete. You included the last name in the success message; do the same thing with the y/n query: input(f"Are you sure you want to delete record {roll} (y/n) ") EDIT: use fstring
🌐
Python Engineer
python-engineer.com › posts › ask-user-for-input
How to ask the user for input until they give a valid response in Python - Python Engineer
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") continue else: break ... 🚀 Solve 42 programming puzzles over the course of 21 days: Link* * These are affiliate link.
🌐
Click Documentation
click.palletsprojects.com › en › stable › prompts
User Input Prompts — Click Documentation (8.3.x)
This can be accomplished with the prompt() function, which asks for valid input according to a type, or the confirm() function, which asks for confirmation (yes/no).
🌐
Linux Hint
linuxhint.com › python_pause_user_input
Python Pause For User Input – Linux Hint
sleep() method can be used to pause the user input for a certain period of time. In the following script, a simple addition task is given for the user. sleep() method is used here to wait for the user for 5 seconds before typing the answer. Next, if the condition is used to check the answer ...
🌐
Reddit
reddit.com › r/learnpython › * h e l p* python not waiting for user to input
r/learnpython on Reddit: * H E L P* python not waiting for user to input
July 6, 2024 -

i have an assignment due tomorrow please help

base_gene = input("""what is the base gene list:
""")
name4Genelist1 = input("\nplease enter a name for the gene list: \n\n")
base_gene_list = list(base_gene.split(","))

compare_gene = input("""what is the gene list you want to compare? :
""")
name4Genelist2 = input("please enter a name for the gene list: ")
compare_gene_list = list(compare_gene.split(","))


# print(base_gene_list)
# print(compare_gene_list)
print(compare_gene_list)
print(base_gene_list)
result = []
for element in compare_gene_list:
    if element not in base_gene_list:
        result.append(element)

result2 = []
for element in base_gene_list:
    if element not in compare_gene_list:
        result2.append(element)

OutPut = ','.join(result)
OutPut2 = ','.join(result2)
print("here is the stuff the was in "+ name4Genelist1 +" gene list and wasnt in " + name4Genelist2 + """:
"""+OutPut)
print("")
print("and here is the stuff the was in "+ name4Genelist2 +" gene list and wasn't in " + name4Genelist1 + """:
"""+OutPut2)
Top answer
1 of 2
4
  • characters should be named Character
  • Add some type hints
  • Use f-strings
  • Use int or float for power score, not str
  • Use a @property where appropriate
  • As-is, there isn't a lot of advantage to separating your prompt strings into variables
  • For the data method, don't force a print - just return a string and print at the outer level
  • Add a main
  • Square brackets around an input choice implies that it is the default to be selected on 'enter'
  • Simplify your yes/no check to only care about the first letter; anything more complicated isn't all that useful
  • Add an input validation loop

Suggested:

class Character:
    def __init__(
        self,
        title: str,
        name: str,
        power_score: int,
        biography: str = 'Not much is known about this character',
    ):
        self.title = title
        self.name = name
        self.power_score = power_score
        self.biography = biography

    @property
    def full_name(self) -> str:
        return f'{self.title} {self.name}'

    @property
    def data(self) -> str:
        return (
            f'{self.title} {self.name} | Power score - {self.power_score} -\n'
            f'{self.biography}'
        )


def ascii_art():
    # Y(Height) of ascii-art
    z = 12
    for x in range(z):
        hyphens = "-" * (z-x)
        print(hyphens + "*" * x + " " * x + hyphens)


def input_yesno(prompt: str) -> bool:
    full_prompt = f'{prompt} ([Yes]/No): '
    while True:
        answer = input(full_prompt).strip()
        if answer == '':
            return True

        answer = answer[0].lower()
        if answer == 'y':
            return True
        if answer == 'n':
            return False
        print('ERROR')


def main():
    ascii_art()
    if not input_yesno('Are you ready to play'):
        return

    is_hero = input_yesno('Do you want to be a Hero')
    print('\nYou have selected', end=' ')
    if is_hero:
        print('to be a hero')
        character = Character('Barbarian', 'Cider', 4854)
    else:
        print('not to be a hero')
        character = Character('Lord', 'Cido', 7910)

    print("\nYour character's profile:")
    print(character.data)


if __name__ == '__main__':
    main()
2 of 2
2

Your updated code looks way cleaner already. Your membership tests answer in yesAnswers / answer in noAnswers are obviously not performance critical here. But in general (especially on large datasets) it's preferrable to use sets for membership tests since they can provide membership information in constant instead of linear time.

Examples:

yesAnswers = {'yes', 'y', 'sure!', ''}

or

noAnswers = set('no', 'n', 'nope')
🌐
GitHub
gist.github.com › r0dn0r › d75b22a45f064b24e42585c4cc3a30a0
Python: wait for input(), else continue after x seconds · GitHub
If there is input, then it will return a list of objects from which input can be read, and only then you read the input. Here: def _wait_for_enter(channel: queue.Queue, timeout: int = None): (rlist, wlist, xlist) = select([stdin], [], [], timeout) if len(rlist): line = stdin.readline() channel.put(line)
🌐
ActiveState
code.activestate.com › recipes › 577058-query-yesno
query yes/no « Python recipes « ActiveState Code
You copy/paste the above code into your current module or a separate one (in that case import it). In this example below I've copy/pasted the recipe into MyModule.py. Then in the module where I want to use it... ... answer = MyModule.query_yes_no("Do you want to use all the .fits files in this directory?") if answer == "no": get_txt_files() else: do_something_else()