In python, is 'foo == (8 or 9)' or 'foo == 8 or foo == 9' more correct?

In python programming, when you are checking if a statement is true, would it be more correct to use foo == (8 or 9)

or foo == 8 or foo == 9

? Is it just a matter of what the programmer wants to do? I am wondering about python 2.7 if different from python 3.

+3


source to share


2 answers


You probably want foo == 8 or foo == 9

, since:

In [411]: foo = 9

In [412]: foo == (8 or 9)
Out[412]: False

In [413]: foo == 8 or foo == 9
Out[413]: True

      

In the end, (8 or 9)

equals 8

:

In [414]: (8 or 9)
Out[414]: 8

      



Alternatively, you can also write

foo in (8, 9)

      

This works for Python3 as well as Python2.

+13


source


foo == (8 or 9)

does not match foo == 8 or foo == 9

, and the latter is the correct form.



(8 or 9)

evaluates 8

to because Python or

evaluates the first operand (from left to right) that is "truthful", or False

, if not, so checking becomes simple foo == 8

.

+2


source







All Articles