DekGenius.com
[ Team LiB ] Previous Section Next Section

9.3 Truth Tests

We introduced the notions of comparison, equality, and truth values in Chapter 7. Since if statements are the first statement that actually uses test results, we'll expand on some of these ideas here. In particular, Python's Boolean operators are a bit different from their counterparts in languages like C. In Python:

  • True means any nonzero number or nonempty object.

  • False means not true: a zero number, empty object, or None.

  • Comparisons and equality tests are applied recursively to data structures.

  • Comparisons and equality tests return 1 or 0 (true or false).

  • Boolean and and or operators return a true or false operand object.

In short, Boolean operators are used to combine the results of other tests. There are three Boolean expression operators in Python:


X and Y

Is true if both X and Y are true


X or Y

Is true if either X or Y are true


not X

Is true if X is false (the expression returns 1 or 0)

Here, X and Y may be any truth value or an expression that returns a truth value (e.g., an equality test, range comparison, and so on). Boolean operators are typed out as words in Python (instead of C's &&, ||, and !). Boolean and and or operators return a true or false object in Python, not an integer 1 or 0. Let's look at a few examples to see how this works:

>>> 2 < 3, 3 < 2        # Less-than: return 1 or 0 
(1, 0)

Magnitude comparisons like these return an integer 1 or 0 as their truth value result. But and and or operators always return an object instead. For or tests, Python evaluates the operand objects from left to right, and returns the first one that is true. Moreover, Python stops at the first true operand it finds; this is usually called short-circuit evaluation, since determining a result short-circuits (terminates) the rest of the expression:

>>> 2 or 3, 3 or 2      # Return left operand if true.
(2, 3)                  # Else return right operand (true or false).
>>> [  ] or 3
3
>>> [  ] or {  }
{  }

In the first line above, both operands are true (2, 3), so Python always stops and returns the one on the left. In the other two tests, the left operand is false, so Python simply evaluates and returns the object on the right (which will happen to have a true or false value if tested). Also, and operations stop as soon as the result is known; in this case, Python evaluates operands from left to right and stops at the first false object:

>>> 2 and 3, 3 and 2    # Return left operand if false.
(3, 2)                  # Else return right operand (true or false).
>>> [  ] and {  }
[  ]
>>> 3 and [  ]
[  ]

Here, both operands are true in the first line, so Python evaluates both sides and returns the object on the right. In the second test, the left operand is false ([ ]), so Python stops and returns it as the test result. In the last test, the left side is true (3), so Python evaluates and returns the object on the right (which happens to be a false [ ]).

The end result of all this is the same as in C and most other languages—you get a value that is logically true of false, if tested in an if or while. However, in Python, Booleans return either the left or right object, not an integer flag.

One final note: as described in Chapter 7, Python 2.3 includes a new Boolean type, named bool, which is internally a subclass of the int integer type, with values True and False. These two instances are really just customized versions of integers 1 and 0, which yield the words True and False when printed or otherwise converted to strings. The only time you'll generally notice this change is when you see Boolean outputs printed as True and False. More on type subclassing in Chapter 23.

Why You Will Care: Booleans

One common way to use the unique behaviour of Python Boolean operators is to select from a set of objects with an or. A statement:

X = A or B or C or None

sets X to the first nonempty (that is, true) object among A, B, and C, or None if all are empty. This turns out to be a fairly common coding paradigm in Python: to select a nonempty among a fixed size set, simply string them together in an or expression.

Short-circuit evaluation is also important to understand, because expressions on the right of a Boolean operator might call functions that do much work or have side effects that won't happen if the short-circuit rule takes effect:

if f1(  ) or f2(  ): ...

Here, if f1 returns a true (or nonempty) value, Python will never run f2. To guarantee that both functions will be run, call them before the or:

tmp1, tmp2 = f1(  ), f2(  )
if tmp1 or tmp2: ...

You'll see another application of this behavior in Chapter 14: because of the way Booleans work, the expression ((A and B) or C) can be used to emulate an if/else statement—almost. Also notice that because all objects are inherently true or false, it's common and easier in Python to test an object directly (if X:) rather than comparing it to an empty value (if X != '':). For a string, the two tests are equivalent.


    [ Team LiB ] Previous Section Next Section