Boolean Values

The Boolean values in Python are True and False, typically used to control if-statements and while-loops.

Boolean And Or Not

The Python "bool" type (short for "boolean") has only two values - True and False. Expressions yielding a bool value like a > 10, can be combined with and or not, like following (printing 'yay' if a is in the range 0..100 inclusive):

if a >= 0 and a <= 100:

Python is unique in using the plain words like "and" for this. many languages use "&&" for and, "||" for or.

a and b → True if both are True

a or b → True if one or the other or both are True

not a → Inverts True/False

Boolean Precedence

There is "precedence" between and/or/not, analogous to arithmetic precedence, where "*" has higher precedence than "+".

Precedence order: not is highest precedence, followed by and, followed by or. Mnemonic: not is like unary minus e.g. '-6', and is like * mutliplication, or is like + addition.

Q: what does the following do:

if a < 6 and b < 6 or c < 6:

The and goes first (higher precedence), so the above is equivalent to the following form with parenthesis added to show the order the comparisons are evaluated:

if (a < 6 and b < 6) or c < 6:

To force the or to go first, put in parenthesis like this:

if a < 6 and (b < 6  or c < 6):

If you are unsure, you can always add parenthesis to an expression to force the order you want.

Boolean Short-Circuit

Suppose you have an int i, and you want to check if the char at that index is alphabetic .. but only if i is valid. You can write that this way...

if i < len(s) and s[i].isalpha():...

This works because the boolean evaluation goes left to right, stopping ("short-circuiting") as soon as it can. So in the example above, if i < len(s) is False (i.e. i is large), the whole expression evaluates to False. In particular the s[i].isalpha() is not evaluated. Attempting to evaluate it would be an error, since i is too large, creating an IndexError.

Writing the i<len(s) test to the left of the s[i] in effect protects it, and this is a common programming pattern. Most computer languages use short circuiting in the their boolean expressions like this.