“真”,并在Python'假' [英] 'True' and 'False' in Python
问题描述
我试图运行这块code的:
路径='/ BLA / BLA / BLA如果路径是正确的:
打印真
其他:
打印假
和它打印的假。我想用Python值对待任何内容的真。为什么会出现这种情况?
从<一个href=\"http://docs.python.org/reference/ex$p$pssions.html#boolean-operations\">http://docs.python.org/reference/ex$p$pssions.html#boolean-operations:
在布尔运算的上下文,还当前pressions通过控制流语句中,以下值PTED为假间$ P $:假,无,所有类型的数字零,空字符串和容器(包括字符串,元组,列表,字典,集和frozensets)。所有其他值都PTED为真际$ P $。
块引用>
块引用>在这里,我想你是误会的关键措辞是PTED为假间$ P $或PTED为真际$ P $。这并不意味着任何这些值是相同的真或假,甚至等于真或假。
这位前pression
/ BLA / BLA / BLA
将被视为真正的,其中一个布尔前pression预期(如在如果
语句),但前pressions/ BLA / BLA / BLA'是真
和/ BLA / BLA / BLA'==真
将评估为False在伊格纳西奥的回答的原因。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 http://docs.python.org/reference/expressions.html#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 anif
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'假'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!