How to repeat loop until a valid answer is given? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
So I coded a function that takes the value of a batteries variable. I want it to do something if the value is "yes" or "no". If the value is none of these answers, I want it to to ask it again for an indefinite amount of times. Here is my code in case my description was bad.
def batterie_answer():
batteries = raw_input("yes or no > ").lower()
print batteries
while True:
if batteries != "yes" or batteries != "no":
print "Please respond yes or no"
raw_input("> ")
continue
elif batteries == "yes":
print "batteries taken!"
items["batteries"] = 1
break
elif batteries == "no":
print "Probably a wise choice. Save some space!"
break
batterie_answer()

You need to move the assignment to inside the while loop or add another assignment. You also need to change the or to an and. You would also need to remove the extra raw_input line that does not assign the value to the batteries variable.
def batterie_answer():
while True:
batteries = raw_input("yes or no > ").lower()
print batteries
if batteries != "yes" and batteries != "no":
print "Please respond yes or no"
continue
elif batteries == "yes":
print "batteries taken!"
items["batteries"] = 1
break
elif batteries == "no":
print "Probably a wise choice. Save some space!"
break
batterie_answer()

The problem is in your if statement. It doesn't matter what value is given, the condition will always equate to true and it will ask again for a value. For example, if the value was "yes" then the condition would be (false or true) which equates to true, if the value was "no" then it would be (true or false) which also equates to true, if the value was something like "asdf" then it would be (true or true) which also equates to true.
to fix this change the "or" operator to an "and" operator.
if batteries != "yes" and batteries != "no":

Your while loop doesn't include the original raw_input() command, so it's never going to ask for input after the first iteration. Instead, it will only ever print out the answer over and over again.
Move the while True up a few lines so that it encompasses the raw_input() command.

Related

In python, can "!=" be used with "and", "or"? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
result = {}
question = '你叫什么名字? ' #What is your name
question_2 = '如果你能去世界上的任何一个地方度假,你想去哪? ' #If you could go to any place in the world for vacation, where would you like to go?
question_3 = '你愿意让你旁边的人也来参加这个调查吗? (yes/ no) ' #Would you like to let people next to you participate in this survey?
while True:
name = input(question)
place = input(question_2)
result[name] = place #除了yes或者no不允许输入其他字符
while True: #No other characters are allowed except "yes" or "no"
opinion = input(question_3)
if opinion.lower() != 'yes' or 'no':
print('请重新输入') #please enter again
else:
break
if opinion == 'no':
break
No matter what you enter after running, you can't jump out of the loop
if opinion.lower() not in ('yes','no'):
It's normal to change to this, but I'm still curious why something went wrong
Beginners, thanks
Consider this line:
if opinion.lower() != 'yes' or 'no':
So this is how that expression is evaluated (according to order of precedence):
if (opinion.lower() != 'yes') or ('no'):
And 'no' is always evaluated as True. Moreover, it should be option not 'yes' 'and' not 'no' (instead of 'or'). Consider changing it to:
if opinion.lower() != 'yes' and opinion.lower() != 'no':
More shortly,
if opinion.lower() not in ('yes', 'no'):
And this will fix your issue.
result = {}
question = "What is your name"
question_2 = "If you could go to any place in the world for vacation, where would you like to go?"
question_3 = "Would you like to let people next to you participate in this survey?"
while True:
name = input(question)
place = input(question_2)
result[name] = place #除了yes或者no不允许输入其他字符
while True: #No other characters are allowed except "yes" or "no"
opinion = input(question_3)
if opinion.lower() not in ('yes','no'):
print('please enter again')
else:
break
if opinion == 'no':
break
You could use a tuple to fix your problem, that's one thing first.
Now what you want is why isn't the following code working:
x != "yes" or "no"
Recall from the order of precedence that != has a higher priority than or, so x!= "yes" will be evaluated first, then it will be ORed with "no", simply to fix it, add parenthesis around the or statement:
x != ("yes" or "no")
Would do the trick for ya!

How to fix the logical error in my while loop? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
Hello programmers of StackOverFlow, I am a teenager that studies Python, And I can't find the logical errors in one of my codes. I wish you could help with that.
I got two logical errors.
1. If the answer is "yes" or "no" it keeps opening the while commands while it shouldn't.
2. Concluding from first error it never stops when the choice == "yes" or "no"..
My coding is here:
choice = raw_input("Do you like programming? (yes/no) : ")
while choice != "yes" or "no":
choice = raw_input('Come on, answer with a "yes" or with a "no" ! : ')
if choice == "yes":
print "I like you !"
elif choice == "no":
print "I am sorry to hear that .. "
, Thank you in advance !
the second line evaluates to True. Because the string "no" evaluates to true
try the following
if "any string": print(1) #will always print 1, unless the string is empty
What you should use instead is
while choice not in ["yes", "no"]:
which checks if choice matches either "yes" or "no"
This is the problem:
while choice != "yes" or "no":
This is interpreted by Python as (choice != "yes") or ("no"). Since "no" is a string of non-zero length, it is truthy. This makes the or expression true because anything OR true is true. So your condition is always true and the loop never stops.
It should be:
while choice != "yes" and choice != "no":
Or:
while choice not in ("yes", "no"):

Infinite while loop Python [duplicate]

This question already has an answer here:
exit an infinite loop? [duplicate]
(1 answer)
Closed 6 years ago.
A little backstory: I have to make a code in Python that helps the user troubleshoot their phone for a school project. The user must only answer 'yes' or 'no' to the questions the program asks.
The issue I''m having is that inputting something other than 'Yes' or 'No'causes the while loop to loop infinitely instead of displaying just once and moving on to the next question once the user types 'Yes' or 'No'.
The code isn't finished yet, which is why it may look like some of the advice/questions are missing.
EDIT: The code functions properly now! Thanks for your answers, guys! They were really helpful!
phoneFault = raw_input("Is your phone physically damaged?")
while phoneFault != "Yes" and phoneFault != "No":
print("Error; you can only answer 'Yes' or 'No' to the questions.")
if phoneFault == "Yes" or phoneFault == "yes":
phoneFault = raw_input("Is your phone wet?")
if phoneFault == "Yes" or phoneFault == "yes":
phoneFault = raw_input("Are you able to turn it off?")
if phoneFault == "Yes" or phoneFault == "yes":
print("Send the phone to the manufacturer and ask if they can fix it.")
elif phoneFault == "No" or phoneFault == "no":
print("Dry the phone, and then wait for the phone to run out of power and then restart it.")
while phoneFault != "Yes" and phoneFault != "No":
print("Error; you can only answer 'Yes' or 'No' to the questions.")
This line is the culprit. As soon as someone inputs something other than "Yes" or "No" we enter this while loop. During this while loop, the value of phoneFault remains unchanged and therefore we continue to print the error message infinitely.
If you add the ability to change the phoneFault value during this while loop, it will solve your problem.
Whenever you get an infinite loop, look at the condition, then look what might alter that condition. You probably want something like this, put the raw_input inside the loop:
phoneFault = None
while phoneFault != "Yes" and phoneFault != "No":
phoneFault = raw_input("Is your phone physically damaged?")
print("Error; you can only answer 'Yes' or 'No' to the questions.")
That's not very user friendly though. Having to press < shift > to get a capital Y or N. You might consider this instead:
phoneFault = None
while phoneFault != "yes" and phoneFault != "no":
phoneFault = raw_input("Is your phone physically damaged (Yes/No)? ").lower()
Although you only have two answers per if condition, I personally prefer the if phoneFault in ('Yes','yes'):membership test. This makes the code more readable. In case you want phoneFault to match anything resembling 'yes' or 'no', you might be interested in regular expressions from the re module.

In this if statement when i type no in the raw_input it is going through the yes part. How do i fix it? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
When I type no into the input on the terminal. It goes through the if choice == "yes" part.
I want it to go through the else. Please help.
choice=raw_input("Will you help us? Yes or no?")
if choice == "yes" or "Yes":
print "Yeah! You are a hero!"
name = raw_input("What is your name?")
print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."
else:
print "You're a coward. :("
quit()
What's wrong?
The bug is in this line of code:
if choice == "yes" or "Yes":
Python sees this as an "or" of two conditions:
if (choice == "yes") or ("Yes"):
Which is same as:
if (choice == "yes") or True:
because a non-empty string is always True.
And this finally reduces to:
if True:
as "or"ing with True always evaluates to True.
This would give you the desired result:
if choice == "yes" or choice == "Yes":
However, that is considered C-style and the pythonic way of comparing multiple values is:
if choice in ("yes", "Yes"):
But in this case, you just want to do a case-insensitive match. So the right way to do that would be:
if choice.lower() == "yes":
And this would even handle odd capitalization in inputs like "yEs" or "YEs".
choice=raw_input("Will you help us? Yes or no?")
if choice == "yes" or choice == "Yes":
print "Yeah! You are a hero!"
name = raw_input("What is your name?")
print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."
else:
print "You're a coward. :("
quit()
The above is the correct format. You did not have the logic set up correctly. Note the following:
a = 1
if a == 2 or 3 :
print 'OK'
It prints 'OK'. Why?
The reason is that python values are evaluated in a left to right fashion. If any value is true then that value is returned. However if all values are false then the last value is returned, in your case 'Yes'. This is what is causing you problems as far as I understand it. You need basically two 'or' conditions, not one....

If-elif-else statement not working in simple Python 3.3 class?

My code is:
def nameAndConfirm():
global name,confirm
print("What is your name? ")
name = input()
str(name)
print("Is",name,"correct? ")
confirm = input()
str(confirm)
print(confirm)
if confirm.upper() == "Y" or "YES":
classSelection()
elif confirm.upper() == "N" or "NO":
nameAndConfirm()
else:
print("Valid answers are Y/Yes or N/No!")
nameAndConfirm()
nameAndConfirm()
Critique on this code would be nice as well. I know its very shifty, I know how to make it shorter in some ways but I was trying to get my if-elif-else to work. I have no clue what else I can do as I've tried everything I know. Also I made an indent 4 spaces in the above code. **Edit: sorry the error is that it always runs the "if" it never goes past the first if line no matter what you enter in for confirm
The condition confirm.upper() == "Y" or "YES" and the other one are not evaluated as you expect. You want
confirm.upper() in {"Y", "YES"}
or
confirm.upper() == "Y" or confirm.upper() == "YES"
Your condition is equivalent to:
(confirm.upper() == "Y") or "YES"
which is always truthy:
In [1]: True or "Yes"
Out[1]: True
In [2]: False or "Yes"
Out[2]: 'Yes'
On a separate note, the lines
str(name)
and
str(confirm)
don't do anything. The values returned by the functions are not saved anywhere, and name and confirm are not altered. Moreover, they are already strings to begin with, because they hold the return values of input().

Categories