next up previous contents index
Next: top Up: Fruitful functions Previous: top   Contents   Index

startsection section 1 0mm-3.5ex plus -1ex minus -.2ex0.7ex plus.2exBoolean functions

Functions can return boolean values, which is often convenient for hiding complicated tests inside functions. For example:


def isDivisible(x, y):
  if x % y == 0:
    return 1       # it's true
  else:
    return 0       # it's false

The name of this function is isDivisible. It is common to give boolean functions names that sound like yes/no questions. isDivisible returns either 1 or 0 to indicate whether the x is or is not divisible by y.

We can make the function more concise by taking advantage of the fact that the condition of the if statement is itself a boolean expression. We can return it directly, avoiding the if statement altogether:


def isDivisible(x, y):
  return x % y == 0

This session shows the new function in action:


>>>   isDivisible(6, 4)
0
>>>   isDivisible(6, 3)
1

Boolean functions are often used in conditional statements:


if isDivisible(x, y):
  print "x is divisible by y"
else:
  print "x is not divisible by y"

If might be tempting to write something like:


if isDivisible(x, y) == 1:

But the extra comparison is unnecessary.

As an exercise, write a function isBetween(x, y, z) that returns 1 if $y \le x \le z$ or 0 otherwise.


next up previous contents index
Next: top Up: Fruitful functions Previous: top   Contents   Index
root 2004-05-05