【发布时间】:2020-07-08 15:15:14
【问题描述】:
我在 python 中遇到了以下表达式来评估一个数字是奇数还是偶数。虽然它看起来很优雅,但我很惊讶地看到它起作用了。我猜输入3:
x%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'
【问题讨论】:
-
True and "odd"计算结果为"odd"。
标签: python lambda boolean-logic evaluation expression-evaluation