I would appreciate some help with this:
I try to make a form-program of the "Then why worry" philosophy:
I wrote this code, but I can't understand how do I make the while loop repeat itself every time the user doesn't enter "yes" or "no" in both questions.
problem = str(input("Do you have a problem in life? "))
problem = problem.replace(" ", "").lower() #nevermind caps or spaces
while problem:
if problem not in ("yes","no"):
print("Please enter YES or NO")
if problem == "no":
break
if problem == "yes":
something = str(input("Do you have something to do about it? "))
something = something.replace(" ","").lower()
while something:
if something not in ("yes","no"):
print("Please enter YES or NO")
elif:
break
print("Then why worry?")
Your algorithm is linear, there is no loops in there. So, the only place you need a loop is when you try to get correct response from the user. So, I'd propose you to move that into a function and then your example turns into this:
def get_user_input(prompt):
while True:
reply = input(prompt).replace(" ", "").lower()
if reply in ['yes', 'no']:
return reply
print("Please enter YES or NO")
problem_exists = get_user_input("Do you have a problem in life? ")
if problem_exists == 'yes':
action_possible = get_user_input("Do you have something to do about it? ")
print("Then why worry?")
I'd suggest to use while True loops, so you can put the input code once, then with the correct condition and break you're ok
while True:
problem = input("Do you have a problem in life? ").lower().strip()
if problem not in ("yes", "no"):
print("Please enter YES or NO")
continue
if problem == "no":
break
while True:
something = input("Do you have something to do about it? ").lower().strip()
if something not in ("yes", "no"):
print("Please enter YES or NO")
continue
break
break
print("Then why worry?")
Using walrus operator (py>=3.8) that could be done easier
while (problem := input("Do you have a problem in life? ").lower().strip()) not in ("yes", "no"):
pass
if problem == "yes":
while (something := input("Do you have something to do about it? ").lower().strip()) not in ("yes", "no"):
pass
print("Then why worry?")
Related
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()
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.
If you ask someone a yes/no question then the answer is one of these two options. In programming what if the response was "Y" or "y" or "yes" or whatever?
I had to create a compound condition repeating my statement while its actually the same one. I'm not an expert but I can see that it can be improved.
def note_maker(note):
case_note = open("case_note.txt", "a+")
update = case_note.write("\n" + note)
multiple_inputs = input("Do you want to enter more details? Y/N")
while multiple_inputs == "yes" or multiple_inputs == "YES" or multiple_inputs == "Yes" or multiple_inputs == "Y" or multiple_inputs == "y":
update_again = case_note.write("\n" + input("Enter your additional information"))
multiple_inputs = input("Do you want to enter more details?")
case_note.close()
Is there a way to control the user input into what I expect?
You can shorten the user input and make it lowercase which should help.
Eg: user_input = input("Something? y/n: ")[0].lower()
This way, if they enter "Y", "Yes", "yes", or "yep" it will end up being "y".
Try refactoring input check into a new function:
def is_affirmative(input: str) -> bool:
return input.strip().lower() in ['y', 'yes']
def note_maker(note):
case_note = open("case_note.txt", "a+")
update = case_note.write("\n" + note)
multiple_inputs = input("Do you want to enter more details? Y/N")
while not is_affirmative(multiple_inputs):
update_again = case_note.write("\n" + input("Enter your additional information"))
multiple_inputs = input("Do you want to enter more details?")
case_note.close()
You could have a set of valid yes responses and no responses:
yes_responses, no_responses = {'y', 'yes'}, {'n', 'no'}
user_response = None
while user_response not in yes_responses and user_response not in no_responses:
user_response = input("Do you want to enter more details? (Y/N): ").lower()
if user_response in yes_responses:
print("The user responded yes.")
else:
print("The user responded no.")
Example Usage:
Do you want to enter more details? (Y/N): zxc
Do you want to enter more details? (Y/N): YesNo
Do you want to enter more details? (Y/N): yEs
The user responded yes.
Note: The advantage of using a set over a list or a tuple is that is the in operation is O(1) rather than O(N).
This is my code
name=""
name=input("What is your name?")
print ("For clarification, is your name",name,"?")
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
and I was wondering if anyone could help me sort it out. In the lines below.
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
print ("Thank you",name,)
I am trying to ask people if they have put the correct names by asking them directly. If the answer is yes, they can move on, otherwise they will have to input their name again. Unfortunately I am not able to find the way to do it. Can anyone send me a correct code version. (An explanation would be nice but not necessary.)
Try :
while True:
n = input("Please enter yes or no")
if n == "yes":
print ("Thank you")
break
else:
name = input("What is your name?")
print ("Thank you",name)
You need to remember the second input to use it in the if statement.
response = input("Please enter yes or no")
if response == "yes":
print("Thank you")
else:
name = input("What is your name?")
You could use a recursive function.
It will loop until it returns the name.
#!python3
def get_name():
name=input("What is your name?")
print("For clarification, is your name",name,"?")
sure = input("Please enter yes or no")
if sure==("yes"):
print("Thank you")
return name
else:
get_name()
name = get_name()
python,please help. I want this code to ask someone if they are ok with the grade. if they say yes, it prints good! if they say no, it says oh well! if they dont say yes or no, i want it to print " please enter yes or no" and keep asking them that until they finally say yes or no. This is what i have so far and when i run it and DONT type yes or no, it spams "please enter yes or no" millions of time
theanswer= raw_input("Are you ok with that grade?")
while theanswer:
if theanswer == ("yes"):
print ("good!")
break
elif theanswer == ("no"):
print ("oh well")
break
else:
print "enter yes or no"
what do i need to do so that it works, ive been trying a lot
You need to have a blocking call in your else statement. Otherwise you will have an infinite loop because theanswer will always be true. Like asking for input:
theanswer= raw_input("Are you ok with that grade?")
while theanswer:
if theanswer == ("yes"):
print ("good!")
break
elif theanswer == ("no"):
print ("oh well")
break
else:
theanswer= raw_input("Please enter yes or no")
Here is a good resorce on Blocking vs Non-Blocking I/O. It's an important fundamental in any application.
or this (this separates the input logic from what you do with the answer):
theanswer = raw_input("Are you ok with that grade?")
while theanswer not in ('yes', 'no'):
theanswer = raw_input('Please enter yes or no')
if theanswer == "yes":
print("good!")
elif theanswer == "no":
print("oh well")
Basically in your code you have a while loop running that will only break if theanswer == yes or == no.
You are also not giving the possibility of changing the value of theanswer in your loop therefore => infinity loop.
add this to your code:
else:
print "enter yes or no"
theanswer= raw_input("Are you ok with that grade?")
This can be accomplished with recursion
def get_user_input(text):
theanswer= raw_input(text)
if theanswer == 'yes':
print('good!')
elif theanswer == ("no"):
print('oh well')
else:
get_user_input('enter yes or no')
get_user_input('Are you ok with that grade?')