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 OverflowAs 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
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'")
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
Using "if input" for a yes/no prompt
Newbie question - Programming help
Identify when python script is waiting for a manual input - Unix & Linux Stack Exchange
ParseError: bad input on line 4
answer = input("Enter yes or no: ")
if answer == "yes":
# Do this.
elif answer == "no":
# Do that.
else: print("Please enter yes or no.")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...')
breaki 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)charactersshould be namedCharacter- Add some type hints
- Use f-strings
- Use
intorfloatfor power score, notstr - Use a
@propertywhere 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()
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')
In Python 3, use input():
input("Press Enter to continue...")
In Python 2, use raw_input():
raw_input("Press Enter to continue...")
This only waits for the user to press enter though.
On Windows/DOS, one might want to use msvcrt. The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT):
import msvcrt as m
def wait():
m.getch()
This should wait for a key press.
Notes:
In Python 3, raw_input() does not exist.
In Python 2, input(prompt) is equivalent to eval(raw_input(prompt)).
In Python 3, use input():
input("Press Enter to continue...")
In Python 2, use raw_input():
raw_input("Press Enter to continue...")