Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...