首页 > 解决方案 > python表达式的评估

问题描述

我在 python 中遇到了以下表达式来评估一个数字是奇数还是偶数。虽然它看起来很优雅,但我很惊讶地看到它起作用了。我猜对于输入3x%2等于1计算结果为True,非空字符串(odd)计算结果为True。所以我们有True and True or <don't have to check because it doesn't matter if True or False as the overall statement will be True>. 但是为什么在那种情况下的输出不是True-odd我错过了什么概念?

>>> (lambda x:
... (x % 2 and 'odd' or 'even'))(3)
'odd'

标签: pythonlambdaboolean-logicevaluationexpression-evaluation

解决方案


andandor运算符不限于 True 和 False ;他们返回他们的操作数之一。

>>> 1 and "odd"
'odd'
>>> 0 or "even"
'even'

推荐阅读