8. Boolean Functions

We have already seen that boolean values result from the evaluation of boolean expressions. The result of any expression evaluation can be returned by a function (using the return statement). In other words, functions can return boolean values. This turns out to be a very convenient way to hide the details of complicated tests. For example:

The name of this function is is_divisible. It is common to give boolean functions names that sound like yes/no questions. is_divisible returns either True or False 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 is_divisible(x, y):
    return x % y == 0

Boolean functions are often used in conditional statements:

if is_divisible(x, y):
    ... # do something ...
    ... # do something else ...

It might be tempting to write something like if is_divisible(x, y) == True: but the extra comparison is not necessary. The following example shows the is_divisible function at work. Notice how descriptive the code is when we move the testing details into a boolean function. Try it with a few other arguments to see what is printed.

Here is the same program in codelens. When we evaluate the if statement in the main part of the program, the evaluation of the boolean expression causes a call to the is_divisible function. This is very easy to see in codelens.


Check your understanding