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 is_divisible(x: int, y: int) -> bool:
2
    result: bool
3
    if x % y == 0:
4
        result = True
5
    else:
6
        result = False
7
8
    return result
9
10
def main() -> None:
11
    print(str(is_divisible(10, 5)))
12
    return None
13
14
main()
15

(ch06_boolfun1)

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: int, y: int) -> bool:
    return x % y == 0

Boolean functions are often used in conditional statements:

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

It might be tempting to write something like if is_divisible(x, y) == True: but the extra comparison is redundant. You only need an == expression if you are comparing some other type than boolean. (is_divisible(x, y) == False can also be made more concise as not is_divisible(x, y)). 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 actual parameters to see what is printed.

12
 
1
def is_divisible(x: int, y: int) -> bool:
2
    return x % y == 0
3
4
def main() -> None:
5
    if is_divisible(10, 5):
6
        print("That works")
7
    else:
8
        print("Those values are no good")
9
    return None
10
11
main()
12

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

Python 3.3
1def is_divisible(x: int, y: int) -> bool:
2    return x % y == 0
3
4def main() -> None:
5    if is_divisible(10, 5):
6        print("That works")
7    else:
8        print("Those values are no good")
9    return None
10
11main()
Step 1 of 11
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 a Python function (assuming x, y and z are defined to be numbers)?

return x + y < z



You have attempted 1 of 6 activities on this page
Next Section - 7.9. Assert Statements