7.8. Boolean Functions

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

 
1
def isDivisible(x, y):
2
    if x % y == 0:
3
        result = True
4
    else:
5
        result = False
6
7
    return result
8
9
print(isDivisible(10, 5))
10

(ch06_boolfun1)

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

Boolean functions are often used in conditional statements:

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

It might be tempting to write something like if isDivisible(x, y) == True: but the extra comparison is not necessary. The following example shows the isDivisible 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 actual parameters to see what is printed.

13
 
1
def isDivisible(x, y):
2
    if x % y == 0:
3
        result = True
4
    else:
5
        result = False
6
7
    return result
8
9
if isDivisible(10, 5):
10
    print("That works")
11
else:
12
    print("Those values are no good")
13

(ch06_boolfun2)

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 isDivisible function. This is very easy to see in codelens.

Python 2.7
1def isDivisible(x, y):
2    if x % y == 0:
3        result = True
4    else:
5        result = False
6
7    return result
8
9if isDivisible(10, 5):
10    print("That works")
11else:
12    print("Those values are no good")
Step 1 of 8
line that has just executed

next line to execute

Frames
Objects

(ch06_boolcodelens)

Check your understanding

select-8-1: What is a Boolean function?




select-8-2: Is the following statement legal in Python (assuming x, y and z are defined to be numbers)?

return x + y < z



Note

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

3
 
1
2
3

(scratch_06_03)

Next Section - 7.9. Glossary