问题
I am drawing a blank on this one too. Rather than provide an answer, I would appreciate if someone could help me understand why my code is not printing the expected output:
def bool_to_str(bval):
if bval is True:
mytest = 'Yes'
else:
mytest = 'No'
return mytest
Expected output:
>>>bool_to_str([1, 2, 3])
'Yes'
>>>bool_to_str(abcdef)
'Yes'
What's actually output:
>>>bool_to_str([1, 2, 3])
'No'
>>>bool_to_str(abcdef)
'No'
Please help me to understand what I did wrong. I think that the function needs to test the actual truth value of the argument, but I don't understand what I'm missing.
回答1:
The is
checks reference equality, not truthiness. Now clearly [1,2,3]
(which is a list
object) does not point to the True
object (which is bool
object). It is hard to say if abcdef
which is not defined here points to True
. But since you do not provide it, I gonna assume it points to something different.
Only bool_to_str(True)
or bool_to_str(<expr>)
where <expr>
evaluates to a bool
that is True
will result in 'Yes'
(the bool
s are singletons, so all True
s are the same object).
The point is that in order to check the truthness of <expr>
, simply write if <expr>:
. So in your case it should be:
if bval:
You can also - although I advise against it, check the truthness explicitly with bool(..)
and check reference equality like:
if bool(bval) is True:
Usually it is not a good idea to write is
. Only if you want to check if two variables point to the same (i.e. not equivalent) object, or for some singleton objects like True
, None
, ()
, etc. it makes really sense.
回答2:
bval is True
checks to see whether [1, 2, 3]
actually is the True object. You need something like bool()
to evaluate whether an object is a true value but not identical to the True object.
回答3:
[1,2,3]
does not equal True
, however, if you put in something like 1
, then 1 == True
would pass but when you use is
it will always be False unless it is True
来源:https://stackoverflow.com/questions/42895080/testing-truthy-or-falsy-arguments-passed-through-a-function-into-an-if-statement