【问题标题】:Evaluation of python expression [duplicate]python表达式的评估[重复]
【发布时间】:2020-07-08 15:15:14
【问题描述】:

我在 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'

【问题讨论】:

  • True and "odd" 计算结果为 "odd"

标签: python lambda boolean-logic evaluation expression-evaluation


【解决方案1】:

andor 运算符不限于 True 和 False;他们返回其中一个操作数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2010-10-22
    • 2015-06-26
    • 2018-06-06
    • 1970-01-01
    • 2016-05-04
    相关资源
    最近更新 更多