为什么布尔表达式print(False == True and not True)运行结果为False?
布尔表达式结果不符合预期的原因说明
你产生预期偏差的核心原因是对Python的运算符优先级规则理解有误,按官方规则拆解False == True and not True的计算过程就能明确问题:
- 首先明确相关运算符的优先级从高到低排序为:
not> 比较运算符(==)>and - 正确计算步骤:
- 优先计算优先级最高的
not True,得到结果False,表达式简化为False == True and False - 其次计算优先级次高的比较运算
False == True,得到结果False,表达式简化为False and False - 最后计算
and运算:and左侧为假时直接返回假,最终结果为False
- 优先计算优先级最高的
- 你预期得到
True,大概率是默认按照错误的运算顺序做了计算,比如误以为运算顺序是False == (True and not True):
按这个错误顺序计算时,True and not True结果为False,False == False结果为True,刚好匹配你的预期,但这个运算顺序不符合Python的官方优先级规则。
如果要得到你预期的结果,需要手动给要优先计算的部分加上括号,即修改表达式为print(False == (True and not True))。
内容的提问来源于stack exchange,提问作者Emily
相关产品推荐
相关产品推荐

