简体   繁体   中英

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

When programming in python, 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 chooses to do? I am wondering about python 2.7, in case it is different in python 3.

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

After all, (8 or 9) is equal to 8 :

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

Alternatively, you could also write

foo in (8, 9)

This holds for Python3 as well as Python2.

foo == (8 or 9) is not the same as foo == 8 or foo == 9 and the latter is the correct form.

(8 or 9) evaluates to 8 since in Python or evaluates to the first operand (left to right) that is 'truthy', or False if neither is, so the check becomes a plain foo == 8 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM