Python Return Boolean (True/False) From Function

4.7/5 - (3 votes)

Do you need to create a function that returns a Boolean (True or False) but you don’t know how? No worries, in sixty seconds, you’ll know! Go! πŸ”₯πŸ”₯πŸ”₯

A Python function can return any object such as a Boolean value (True or False). To return a Boolean, you can have an arbitrary simple or complex expression within the function body and put the result of this after the return keyword (e.g., return False).

πŸ‘‰ Recommended Tutorial: The return keyword in Python

Boolean Function – Minimal Example

Let’s have a look at a minimal example that creates a function boo() that returns one Boolean value False and does nothing else:

def boo():
    return False

# False

Where would you use such a function?

In many cases, you want to use the Boolean function in a conditional statement such as if expression or a while loop to determine the execution branch.

The following example shows how the boo() function returns the Boolean value False and is called directly within an if condition to determine the execution branch.

In the example, we visit the else branch because the function returns False.

if boo():

# Output: Nay

Boolean Function – More Practical Example

A more practical example would be the following function that checks for a given integer argument whether it is an even or odd number.

  • If the argument is even, it returns True.
  • If the argument is odd, it returns False.

def is_even(x):
    ''' Returns True if x is an even number and False otherwise.'''
    if x%2 == 0:
        return True
        return False

We use the modulo operator to determine whether the number is divisible by 2 without remainder, i.e., the definition of an even number.

πŸ‘‰ Recommended Tutorial: Python Modulo Operator — A Simple Guide

We can use the function is_even() to guess a random number until we get an odd number by a simple guess-and-check routine:

import random

x = random.randint(0, 9)
while is_even(x):
    x = random.randint(0, 9)

Of course, this is non-deterministic, so we don’t know which output it will produce. We only know that the print() statement will for sure print an odd number. In my case, the output was 3.

πŸ’‘ Note: A much more concise way to write the same function would be the following one-liner expression not bool(x%2) that uses the bool() function, the modulo operator % and the not operator.

def is_even(x): return not bool(x%2)

# True

# False

Related Tutorials

Programmer Humor

Q: How do you tell an introverted computer scientist from an extroverted computer scientist?

A: An extroverted computer scientist looks at your shoes when he talks to you.