lob*_*buo 3 python if-statement boolean python-2.7
在python中编程时,当您检查语句是否为真时,使用foo == (8 or 9)或更正确foo == 8 or foo == 9吗?这只是程序员选择做的事情吗?我想知道python 2.7,以防它在python 3中有所不同.
unu*_*tbu 13
你可能想要foo == 8 or foo == 9,因为:
In [411]: foo = 9
In [412]: foo == (8 or 9)
Out[412]: False
In [413]: foo == 8 or foo == 9
Out[413]: True
Run Code Online (Sandbox Code Playgroud)
毕竟,(8 or 9)等于8:
In [414]: (8 or 9)
Out[414]: 8
Run Code Online (Sandbox Code Playgroud)
或者,你也可以写
foo in (8, 9)
Run Code Online (Sandbox Code Playgroud)
这适用于Python3和Python2.