不明白为什么变量为整数时条件求值为True [英] Do not understand why if condition evaluates to True when variable is integer
问题描述
我正在处理表现以下行为的代码.假设我有一个变量d
,并将其分配给一个整数9
I am working with code that exhibits the following behavior. Suppose I have a variable d
and I assign it to an integer 9
d = 9
以下语句为什么起作用?
why do the following statements work?
In [95]: if d:
....: print d
....: else:
....: print 'Did not print d!'
....:
9
In [96]:
当d本身不是布尔值且未通过以下测试时:
when d itself is not a Boolean and does not pass the following tests:
In [96]: d is True
Out[96]: False
In [97]: d is False
Out[97]: False
如果有人可以向我解释一下并指出我的任何误解,我将不胜感激.非常感谢.
I will appreciate it if someone could explain this to me and point out any misconception that I have. Thank you very much.
推荐答案
请记住,is
测试身份.您的d is True
和d is False
语句返回False,因为d
是9
,而不是True
或False
.但是,d
的真实值为True-尝试运行bool(d)
以获得其布尔值(提示:它将返回True
).
Remember, is
tests for identity. Your d is True
and d is False
statements are returning False because d
is 9
, not True
or False
. However, the truthy value of d
is True - try running bool(d)
to get its Boolean value (hint: it'll return True
).
如其他地方所述,False,None,0和空字符串,列表,字典,集合,元组等都被认为是虚假的.根据对象的__nonzero__
和/或__len__
属性(如果已设置)的内容,它们也可能是虚假的.
As stated elsewhere, False, None, 0, and empty strings, lists, dicts, sets, tuples, etc. are all considered falsy. Objects can also be falsy depending on the contents of their __nonzero__
and/or __len__
attributes, if set.
这篇关于不明白为什么变量为整数时条件求值为True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!