In the following code, answer()
works as expected and returns true if input is "y" and false when not, but in answer2()
, it always returns true.
Can someone explain why this is the case?
def answer():
answer = raw_input()
if answer == "y":
return True
else:
return False
def answer2():
answer = raw_input()
if answer == "y" or "yes": # <- notice the extra: or "yes"
return True
else:
return False
if answer() == True:
print "true"
else:
开发者_运维问答print "false"
if answer2() == True:
print "true"
else:
print "false"
The expression, "y" or "yes"
will evaluate to "y"
. What you want is:
if answer in ('y', 'yes'):
return True
I'm not a Python expert, but I suspect in answer2 it should be:
if answer == "y" or answer == "yes": # <- notice the extra: or "yes"
In other words, I suspect it's currently parsing it as:
if (answer == "y") or ("yes")
and just converting "yes" into True, effectively... which is why it's always returning True.
You want
if answer == "y" or answer == "yes":
you have to test it that way.
Or better still, have a list of affirmative responses and test inclusion;
affirmatives = ["yes","y","ja","oui"]
if answer in affirmatives:
It's all to do with boolean (True/False) operators. Check out the following:
>>> "yes" == "yes" or "fnord"
True
>>> "no" == "yes" or "fnord"
'fnord'
If the first part is True, you get True - if the first part is False, you get the right-hand side of the 'or'. Now, by having:
answer == "y" or answer == "yes"
you can see how if the first == returns False it returns the second == test...
you need to say:
if answer == "y" or answer == "yes"
how you did it evaluates as:
if (answer == "y") or "yes"
which will always be true as "yes" is a non-empty string.
if answer == "y" or "yes":
Note that this is different that:
if answer == "y" or answer == "yes":
Because "yes" is a non-zero value, the first one will always return True.
Here's the issue:
answer == 'y' or 'yes'
is always going to return True or 'yes' (effectively True since it is not 0 or None),because it's being evaluated as:
if (answer == 'y') or 'yes'
so you are always going to trigger the 'if' block and return True.
精彩评论