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.
Related
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!
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 4 years ago.
My python code has some errors in the try- except loop. If you enter an input which is not yes or no, it first prints the "yes" reply output, then once you answer the question it shows the output for if you do not enter yes or no. Here's the code:
playAgain = None
while playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n":
try:
playAgain = str(input("Do you want to play again? Enter Yes or No: "))
if playAgain == "Yes" or "y" or "yes":
displayIntro()
elif playAgain == "No" or "no" or "n":
print("Oh, well. The magic 8 ball will see you next time...")
sys.exit()
except:
print("That wasn't yes or no, idiot. The magic 8 ball will not give a fortune to such an imbocile.")
Please help and thank you!
playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n"
Is not a correct way to do this.
When you say playAgain != "Yes" then you need to do the same for the remaining expression. So a valid way to do what you were intended to do is the following:
playAgain != "Yes" or playAgain != "No" or playAgain != "yes" or playAgain != "no" or playAgain != "y" or playAgain != "n"
But this is ugly and too long.
Instead, use
playAgain not in ["Yes", "No", "yes", "no", "y", "n"]
In Python, we have some handy ways to deal with such problems. You can use the in operator to check if the string in question exists (or does not exist) in a list of possible values. It's also very nice to read: "if playAgain (is) not in [this list of values]".
You can even manipulate the input so it's easier for you to work with. That is, you lower all the letters and you don't check for case-sensitive input (if you really don't care about case sensitive input; do you really care if is Yes or yEs?):
playAgain.lower() not in ["yes", "y"]
Something like this should do:
while True:
playAgain = str(input("Do you want to play again? Enter Yes or No: "))
if playAgain.lower() in ["yes", "y"]:
# do something with your yes input. Consider `break` out of the endless loop.
elif playAgain.lower() in ["no", "n"]:
# do something with your no input. Consider `break` out of the endless loop.
else:
print("That wasn't yes or no.")
Note that the above loop is endless. You need to break-out according to your program logic. That is, you need to put a break statement somewhere when you need to break out of the endless loop.
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"):
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.
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....