python - 不明白为什么当变量为整数时 if 条件的计算结果为 True

标签 python variables if-statement int boolean

我正在使用表现出以下行为的代码。假设我有一个变量 d 并将其分配给一个整数 9

d = 9

为什么下面的语句有效?

In [95]: if d:
   ....:     print d
   ....: else:
   ....:     print 'Did not print d!'
   ....:     
9

In [96]: 

当 d 本身不是 boolean 值且未通过以下测试时:

In [96]: d is True
Out[96]: False

In [97]: d is False
Out[97]: False

如果有人能向我解释这一点并指出我的任何误解,我将不胜感激。非常感谢。

最佳答案

引自official Python documentation ,

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

if 语句属于Booelan 操作的上下文。由于 d9 不属于任何错误值,因此它被视为 Truthy。

你可以这样确认

>>> all(bool(value) is False for value in (False, 0, +0, -0, "", (), [], {}, set()))
True

虽然值 9 既不是 True 也不是 False,你用 d 确定是 Trued is False 测试,由于上述原因,它被认为是 Truthy。

>>> bool(9)
True

关于python - 不明白为什么当变量为整数时 if 条件的计算结果为 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27853301/

相关文章:

JavaScript 没有函数的变量提升

python - 如何将 png 文件转换为 geotiff

python - 将列值与行值匹配并写入新列

c# - 内存不足时释放的动态变量?

CSS 样式表中的 PHP 变量

javascript - Jquery/Javascript 使用 IF/ELSE 语句更改 img SRC

python - Base.html 中 Flask 登录表单的 Bootstrap 模式无需在每个 View 函数中发送表单?

python - 为什么在 Tensorflow 中使用和不使用上下文管理器定义 tf.Session 会导致不同的行为?

python - Python/Django “if statement”语法不正确?

java - 判断一个数是否是质数