测试通过函数传递到if语句的Truthy或Falsy参数 [英] Testing Truthy or Falsy arguments passed through a function into an if statement
问题描述
我也在这一点上画了一个空白。如果有人能帮助我理解为什么我的代码没有打印出预期的输出,我将不胜感激。
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
预期产出:
>>>bool_to_str([1, 2, 3])
'Yes'
>>>bool_to_str(abcdef)
'Yes'
实际输出的是什么:
>>>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,2,3]
(这是一个列表
对象)没有指向 True
object ( bool
对象)。很难说这里没有定义的 abcdef
指向 True
。但是既然你没有提供它,我会假设它指向不同的东西。
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.
只有 bool_to_str(真)
或 bool_to_str(< expr>)
其中< expr>
评估为 bool
即 True
将导致'是'
( bool
s是单身人士,因此所有 True
s都是同一个对象。)
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).
关键是,为了检查< expr>
的真实性,如果< expr>,只需写下 ;:
即可。所以在你的情况下它应该是:
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:
你也可以 - 虽然我建议反对它,用 bool(..)明确检查真相
并检查参考相等如:
You can also - although I advise against it, check the truthness explicitly with bool(..)
and check reference equality like:
if bool(bval) is True:
通常写不是一个好主意
。仅当您要检查两个变量是否指向相同(即不 等效)对象,或者某些单个对象(如<$ c)时$ c> 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.
这篇关于测试通过函数传递到if语句的Truthy或Falsy参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!