I'm a self taught programmer, and I just started using python. I'm having a bit of a problem, when I execute this code:
x = 0
while x == 0:
question = raw_input("Would you like a hint? ")
if question == "y" or "yes":
print "Ok"
first.give_hint("Look over there")
x = 1
elif question == "n" or "no":
print "Ok"
x = 1
else:
print "I'm Sorry, I don't understand that"
just so you know, first.give_hint("Look over there") was defined in a class earlier in the program, I just left that part out for sake of space. When I run the program no matter what I type, I get the first case "Look over There", I've been trying to figure out what the problem is, but I just don't understand. If you guys could help me, I'd appreciate it a lot.
The problem is this line:
if question == "y" or "yes":
"yes" will always evaluate to True.
What you really want is:
if question == "y" or question == "yes":
Similar changes must be made for the other conditions.
You made a mistake in your if statement, this should be :
if (question == "y") or (question == "yes"):
print "Ok"
Explanation :
(question == "y" or "yes")
is equivalent to :
(question == "y" or "yes" != 0) # operator 'or' having the prevalence
"yes" string being non-null, ("yes" != 0) always return True, and so do your whole original condition.
The condition is wrong. You have question == "y" and a logical or with the string "yes" that is always True. That is why it evaluates to the first case every time.
Try to change to if question[0] == 'y'
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:
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:
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....
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
Here is a part of my code where the problem is.
It doesn't matter what the input is, the script will end
when I enter something.
It should restart when i enter "yes" or "y"
Without the OR it works without problem
else:
if number == rndnum:
print "Congratulations! You won."
print "Do you want to replay?"
answer = raw_input("Type y (yes) or n (no): ")
dialog = 1
while dialog == 1:
if answer == "n" or "no":
replay = 0
dialog = 0
elif answer == "y" or "yes":
dialog = 0
else:
answer = raw_input("Type y (yes) or n (no): ")
loop = 0 #Will overdo loop var and stop the loop
if answer == "n" or "no":
is interpreted by Python as:
if (answer == "n") or ("no"):
Which is always true, because the second condition in your or clause is always True (non-empty strings in Python are truthy, which means they evaluate to True in a condition):
>>> bool("no")
True
What you need is one of:
if answer in ("n", "no"):
# or
if answer == "n" or answer == "no":
Th same goes for "yes", of course.
Adjust your code like this:
if answer == "n" or answer == "no":
# ...
and:
elif answer == "y" or answer == "yes":
# ...
a or b, where a and b are strings and not both the empty string, will always evaluate to True in a boolean context, demo:
>>> '' or 'x'
'x'
>>> 'y' or 'x'
'y'
>>> '' or ''
''
>>> if 'x': print('hi')
...
hi
>>> if '': print('hi')
...
>>>
The first two expressions will evaluate to True.
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().