Logical operators

3.5.3. Logical operators#

In section Boolean and comparisons, we learned how to generate boolean values (True, False) using comparison operators such as > (greater than) or <= (less or equal to). We can create more complex comparisons by combining and inverting the results of many comparisons, using the logical operators not, or and and as shown in Fig. 3.6.

Fig. 3.6 Truth table of not, or and and.#

def is_between(a, lower, upper):
    """Returns True if a is strictly between lower and upper."""
    return (a > lower) and (a < upper)


# Test the function
print(is_between(3, 2, 5))
print(is_between(10, 2, 5))
print(is_between(2, 2, 5))
True
False
False

Good practice: Naming functions that return bools

For clarity, functions that return booleans often start with is_, has_, contains_, etc.