示例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()
Run Code Online (Sandbox Code Playgroud)
示例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"
Run Code Online (Sandbox Code Playgroud)
有没有办法将变量与"OR"运算符进行比较,而不是在每一行中重复两次变量?
这是一种等效的方式:
if var in [2, 3]:
...
elif var in [2, 15]:
...
Run Code Online (Sandbox Code Playgroud)
并且您var每个条件只使用一次.
笔记:
OR直接使用.2在第二个状态并没有真正意义.