How can I create a function with Yes or No? - python

How can I go about creating a input and output with Y\N (yes or no) function in a question?
My example; if my question is Would you like some food? (Y \ N):, how can I do this and have the answers show Yes, please. or No, thank you. for either choice and then proceed to the next question with the same function?
I thought about using this: valid=("Y": True, "y": True, "N": False, "n": False) but that only shows up as True or False for me, or is there a way to change from True \ False to Yes \ No? or this one:
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
But I'm really not sure how else to proceed with this one, or if there's any other easier solution to this.

I think what you're looking for is a conditional print statement rather than a true/false return statement on the function.
For example:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
print ("Yes, please" if user_input == 'Y' else "No, thank you")
Or, more readable:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
if (user_input == 'Y'):
print("Yes, please")
elif (user_input == 'N'):
print("No, thank you")

I hope I understood your question correctly, you basically check the first letter (incase user enters yes/no) every time the user enters a value and try to verify that if it's Y/N you break the loop if not you keep asking the same question.
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
if user_input[0].lower() == 'y':
print("Yes, please.")
break
elif user_input[0].lower() == 'n':
please("No, thank you.")
break
else:
print("Invalid, try again...")

Not sure if this is the best way, but I have a class based implementation of same
""" Class Questions """
class Questions:
_input = True
# Can add Multiple Questions
_questions = [
'Question 1', 'Question 2'
]
def ask_question(self):
counter = 0
no_of_question = len(self._questions)
while self._input:
if counter >= no_of_question:
return "You have answred all questions"
user_input = input(self._questions[counter])
self._input = True if user_input.lower() == 'y' else False
counter += 1
return "You have opted to leave"
if __name__ == '__main__':
ques = Questions()
print(ques.ask_question())

Firstly there is many ways you can go around this, but I am guessing you found the solution yourself already but here is one that is the best.
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
continue = get_yes_no_input('Would you like to proceed? [Y/N]: ')
And there we go.

Related

Can't get string user input working (Python)

I've searched the web and this site and been messing around all day, trying 100 ways to get this simple little program working. I'm practicing endless While loops and string user inputs. Can anyone explain what I'm doing wrong? Thank you!
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.islower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
your code has one thing wrong answer.islower() will return boolean values True or False but you want to convert it into lower values so correct method will be answer.lower()
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.lower() # change from islower() to lower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
You just need one amendment to this line:
Instead of
answer = answer.islower()
Change to
answer = answer.lower()

Python: Depending on IF statement output, execute different code outside of itself

If my_input == "n" I want to my program to loop again, which works fine.
But if my else statement is True I dont want it to run the whole program again and just "start" at the my_input variable.
How can I achieve this?
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
else:
print("Invalid input, try again.")
name_user_validation()
I misunderstood your question, I would probably restructure your code a bit, so you get rid of your while loops and use recursive function calling to go back when you need to,
something like the below
def name_user_validation():
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split() # This line actually doesn't do anything
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
if not accept_input():
name_user_validation()
def accept_input():
my_input = input("Is that right? (y/n) ")
if my_input == "y":
print("Great!")
return True
elif my_input == "n":
print("Oh no :(")
return False
else:
print("Invalid input, try again.")
accept_input()
name_user_validation()
Add another loop that doesn't terminate until user enters acceptable input.
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
while True:
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
break
else:
print("Invalid input, try again.")
if my_input == 'y':
break
name_user_validation()
Edit: The program terminates only when my_input = y.

Python: Skip user input and call later on

I'm fairly new to Python and am currently just learning by making some scripts to use at work. Real simple, just takes user input and stores it in a string to be called later on. The questions are yes/no answers but I wish for the user to have the option to skip and for the question to be asked again at the end, how would I do this?
Currently this is what I've got:
import sys
yes = ('yes', 'y')
no = ('no', 'n')
skip = ('skip', 's')
power = str(raw_input("Does the site have power? (Yes/No): "))
if power.lower() in yes:
pass
elif power.lower() in no:
pass
elif power.lower() in skip:
pass
else:
print ''
print '%s is an invlaid input! Please answer with Yes or No' % power
print ''
exit()
then at the end of the script after all the questions have been asked I have this:
if power.lower() in skip:
power = str(raw_input("Does the site have power? (Yes/No): "))
if power.lower() in yes:
pass
elif power.lower() in no:
pass
else:
print ''
print '%s is an invlaid input! Please answer with Yes or No' % power
print ''
exit()
else:
pass
if power.lower == 'yes':
print 'Site has power'
else:
print 'Site doesnt have power, NFF.'
I understand this is very messy and I'm just looking for guidance/help.
Regards,
Trap.
Since you're rather new to Python I'll give you some tips:
Store all the questions which receive "skip" as a response into a list.
At the end of all your questions, iterate through (hint: "for" loop) all the questions which the user skipped and asked them again.
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
message=("is this correct")
Print=(message)
#store input
answer = input("yes/no:")
if answer == "yes": print("thank you")
if answer == "no": print("hmm, are you sure?")
#store input
answer = input("yes/no:")
if answer == "yes" : print("please call my suppot hotline: +47 476 58 266")
if answer == "no" : print("ok goodbye:)")
if someone had a solution for line 7 when answerd yes skiped to the end desplaing ok `goodbye:) thank you`

New Programmer, How do you use If and Elif and Else statements? Its giving me NameError: name 'No' is not defined

answer = input('Hi! Would you like to say something? (No or Yes)')
if answer == No or no:
print('Okay then, have a good day!')
elif answer == Yes or yes:
answertwo = input('What would you like to say?')
print(answertwo, 'Hmmmmmm, Intresting.')
**if answer == No or no:
NameError: name 'No' is not defined**
I would suggest you using .lower() for every input. This ensures that if some types "nO" or "YeS" it takes the lowercase equivalent. Example:
ui = input("Type \"Hi\"").lower()
Next, you should really add an else option to your code. This is for answers you don't want them to type. This should be held in a while loop Example:
while(True):
ui = input("Type \"Hi\"").title()
if(ui == "Hi"):
print("Hello")
break
else:
print("That isn't a choice!")

How to add a progress bar in python?

I've been asked to make a 'Privilege Checker' and so far it is coming along pretty well. Here is my code:
def Privilige():
print("Welcome to Privilege checker V0.011")
print("Would you like to check your privileges?")
answer = input("Type 'Yes' or 'No' and hit enter ('Y', 'y', 'N', or 'n' are also valid choices).")
print("Checking priviliges.")
if answer == "yes" or answer == "Yes" or answer == "Y" or answer == 'y':
print("Privileges: Checked")
elif answer == "no" or answer == "No" or answer == 'N' or answer == 'n':
print("Privileges: Unchecked.")
else:
print("Please enter a valid option.")
Privilige()
Now, in between print("Checking privileges.") and if answer == "yes" I would like to add a progress bar that uses this character, "█" is this possible?
Any help appreciated, thanks!
You could try something like this:
from time import sleep
for i in range(60): # Change this number to make it longer or shorter.
print('█', end='')
sleep(0.1) # Change this number to make it faster or slower.

Categories