官术网_书友最值得收藏!

Using bits and Boolean values

As noted earlier, the bit-oriented operators &, |, ^, and ~ have nothing to do with Python's actual Boolean operators and, or, not, and if-else. We'll look at Boolean values, logic operators, and related programming in Chapter 5, Logic, Comparisons, and Conditions.

If we misuse the bit-oriented operators & or | in place of a logical and or or, things may appear very peculiar:

>>> 5 > 6 & 3 > 1
True
>>> (5 > 6) & (3 > 1)
False

The first example is clearly wrong. Why? This is because the & operator has relatively high priority. It's not a logical connective, it's more like an arithmetic operator. The & operator is performed first: 6&3 evaluates to 2. Given this, the resulting expression, 5 > 2 > 1, is True.

When we group the comparisons to perform them first, we'll get a False for 5>6, and a True for 3>1. When we apply the & operator the result will be False, which is what we expected. Using bit operators inappropriately as logical connectives can work if we use parentheses to be sure that the bit operators are performed last. It's a very bad idea, however.

It's easier, clearer, and altogether better to use the proper Boolean operators shown in Chapter 5, Logic, Comparisons, and Conditions.

主站蜘蛛池模板: 含山县| 韶山市| 师宗县| 阿拉善左旗| 定日县| 嵊州市| 黑龙江省| 石楼县| 吴江市| 五大连池市| 永春县| 凉城县| 司法| 犍为县| 东阳市| 简阳市| 靖安县| 丘北县| 安溪县| 五指山市| 黑龙江省| 舟曲县| 泰兴市| 张家界市| 大兴区| 荆门市| 金湖县| 洛扎县| 老河口市| 沙坪坝区| 岳普湖县| 邵武市| 桐城市| 新建县| 孝昌县| 永兴县| 宣城市| 阳信县| 岗巴县| 清远市| 五莲县|