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:

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.

Run the program using 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

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

  • A function that returns True or False
  • A Boolean function is just like any other function, but it always returns True or False.
  • A function that takes True or False as an argument
  • A Boolean function may take any number of arguments (including 0, though that is rare), of any type.
  • The same as a Boolean expression
  • A Boolean expression is a statement that evaluates to True or False, e.g. 5+3==8. A function is a series of expressions grouped together with a name that are only executed when you call the 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
    
  • Yes
  • It is perfectly valid to return the result of evaluating a Boolean expression.
  • No
  • x +y < z is a valid Boolean expression, which will evaluate to True or False. It is perfectly legal to return True or False from a function, and to have the statement to be evaluated in the same line as the return keyword.
You have attempted of activities on this page
7.7. Chained conditionals"> 7.9. Assert Statements">Next Section - 7.9. Assert Statements