#39;True#39; and #39;False#39; in Python(Python中的“真和“假)
问题描述
我尝试运行这段代码:
path = '/bla/bla/bla'如果路径为真:打印真"别的:打印假"
它会打印 False.我认为 Python 将任何有价值的东西都视为 True.为什么会这样?
来自 6.11.布尔运算:
<块引用><块引用>在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值被解释为假:假、无、所有类型的数字零以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集合).所有其他值都被解释为 true.
我认为您误解的关键短语是解释为假"或解释为真".这并不意味着这些值中的任何一个都等于 True 或 False,甚至等于 True 或 False.
表达式 '/bla/bla/bla'
将在需要布尔表达式(如 if
语句中)的情况下被视为 true,但表达式 '/bla/bla/bla' 是 True
并且 '/bla/bla/bla' == True
将评估为 False 原因在 Ignacio 的回答中.
I tried running this piece of code:
path = '/bla/bla/bla'
if path is True:
print "True"
else:
print "False"
And it prints False. I thought Python treats anything with value as True. Why is this happening?
From 6.11. Boolean operations:
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.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.
这篇关于Python中的“真"和“假"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中的“真"和“假"


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01