Comp 150- Computer Programming 1

Booleans in Python

(March 4, 2008)

 

Like many computer languages, Python implements Boolean values as follows:

 

            A non-zero value is considered to be True

 

            A zero value is considered to be False

 

This is why Python accepts expressions like (0 and 2), (2 or 0), and (3 and 1). Python see them as equivalent to (False and True), (False or True) and (True and True); hence their values are respectively 0, 2 and 1 (or False, True and True) .

 

>>> (0 or 2)

2

>>> (2 or 0)

2

>>> (1 or 3)

1

>>> (3 or 1)

3

>>> (0 and 2)

0

>>> (2 and 0)

0

>>> (1 and 3)

3

>>> (3 and 1)

1

>>> 

 

If we use the bool() type conversion function to type cast the result to be a Boolean we obtain the familiar True and False values. Apply a “not” to an integer results in a True or False depending on whether the integer is zero or non-zero.

 

>>> bool(3 and 1)

True

>>> bool(2 and 0)

False

>>> not 1

False

>>> not 0

True

>>> not 2

False

>>> int (not 2)

0

>>> int (not 0)

1

>>> 

 


 

There is actually a pattern to the above which gives insight into how the and and or Boolean operators work.

 

And returns the first (left) operand if it is 0 (False); otherwise it returns the second (right) operand. This is because if the first operand is 0 (False) then “and-ing” a False value with anything will be trivially False (in fact the evaluation of the expression stops because the result is known; this is called lazy evaluation). If the first operand is non-zero or True, the result depends wholly on the second operand.

 

Or returns the first (left operand) if it is non-zero (True); otherwise it returns the second (right) operand. This is because if the first operand is non-zero (True) then “or-ing” a True value with anything will be trivially True (and again the evaluation of the expression stops because the result is known);  If the first operand is 0 or False the result depends wholly on the second operand.

 

This is why the expression

 

if (month == (1 or 3 or 5 or 7 or 8 or 10 or 12)):

 

will always be False unless month equals 12. And of course this is why we must write this as

 

if ((month == 1) or (month == 3) or (month == 5) or (month == 7) or

    (month == 8) or (month == 10) or (month ==12)):