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

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!

Related

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

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.

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.

Python will not accept user inputs [duplicate]

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 7 years ago.
I managed to get this code to work before, but I've changed something accidentally and can't figure out what.
The code that will not work is:
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
When I run the code and put in one of the answers, the program will not run the next part and gives no error message.
In case it is necessary, I have put the code for the entire program below:
import random
import sys
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
try:
value = int(code)
except:
print ("Invalid code")
continue
if 1 <= value <= 100:
print (code)
print ("Valid code")
print ("I will now try to guess your number")
number = random.randint(1, 100)
while number > int(code) or number < int(code):
print ("Failed attempt. Number guessed is")
number = random.randint(1, 100)
print (number)
else:
if number == int(code):
print ("Your code is")
print (code)
else:
print ("Invalid code")
EDIT: Thank you so much, the yes option is working now, but the program will still not exit when selecting any of the no options, as it did before. The edited code is:
if answer in ('no', 'n', 'No', 'N'):
sys.exit()
elif answer in ('yes', 'y', 'Yes', 'Y'):
I checked by printing the answer value, and i believe it is registering the no input but not executing the command that follows for some reason.
EDIT: I'm still a bit fuzzy on the logic, but changing it to exit() fixed the problem. It asks for confirmation when closing now, when it didn't before, but otherwise sorted.
Problem causing silent exit:
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
That test is testing answer == 'no' as one test, then 'n' as a separate test, and so on. or chains return when any test returns a "truthy" value (or the last evaluated value if none are truthy), so the test always ends up evaluating as "truthy" because a non-empty string like 'n' is truthy. If you're trying to test for any one of those values, you'd do an "is contained in" test to see if answer is one of a recognized group of values, e.g.:
if answer in ('no', 'n', 'No', 'N'):
The reason is due to this expression:
if answer == 'no' or 'n' or 'No' or 'N':
In python, the above is exactly the same as this:
if (answer == 'no') or ('n' != '') or ('No' != '') or ('N' != ''):
Since all but the first expression evaluates to true, the whole expression is true.
The simplest solution is to convert your input to lowercase and trim off any extra space, then check if the answer is in a list of allowable answers so that you can easily compare for "n", "N", "no", "NO", "No", "nO".
if answer.strip().lower() in ("n", "no"):

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