Python OR 运算符和括号

Python OR operator and parenthesis

示例 1 - 这有效:

def thisorthat():
    var = 2

    if (var == 3 or var == 2):
        print "i see the second value"
    elif (var == 2 or var == 15):
        print "I don't see the second value"

thisorthat()

示例 2 - 这不起作用:

def thisorthat():
    var = 2

    if var == (3 or 2):
        print "i see the second value"
    elif var == (2 or 15):
        print "I don't see the second value"

thisorthat() # "I don't see the second value"

有没有一种方法可以将变量与 "OR" 运算符进行比较,而无需在每一行中重复变量两次?

这是一个等效的方法:

if var in [2, 3]:
    ...
elif var in [2, 15]:
    ...

并且您每个条件仅使用一次 var

备注:

  • 这不是直接使用 OR
  • 第二个条件中的2确实没有意义。

对你做错了什么的解释:

在 Python 中,or 并不总是像英语那样工作。它接受两个参数并查看它们中的任何一个是否具有布尔值 True(返回第一个)。所有非零数字都具有布尔值 True,因此 var == (3 or 2) 的计算结果为 var == 3,因为 var 为 2,因此计算结果为 False。当您执行 var == (2 or 15) 时,您会得到 var == 2,这是正确的,因此执行 elif 语句下面的代码。

就像建议的那样,您应该改为 var in (3, 2)