简体   繁体   中英

Why does True & True give False?

>>> 5 > 4 & 6 > 5

Why does the above expression give False in Python, if 5 > 4 is True and 6 > 5 is also True ?

Because & (bitwise "and") has a higher precedence than > , so 5 > 4 & 6 > 5 is actually evaluated as 5 > 4 > 5 which is obviously False .

Operator precedence on Python docs.

In python the & operator represents the bitwise AND operator , which basically takes the binary form of an integer, and masks the binary form of the first number by the second number.

For example, 10 & 3 returns 2 because the binary form of 10 is 1010 , and with the mask of 3 , we take the last three digits, and find the value of the resulting binary. In this case, it's 010 , which in decimal is 2 .

The operator you're looking for is the literal and operator::

>>> 5 > 4 and 6 > 5 
True

Or better (I believe you already know this):

>>> 6 > 5 > 4
True

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