Python中的“真"和“假"

2022-01-19 00:00:00 python boolean

问题描述

我尝试运行这段代码:

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.

相关文章