CPSC120A
Fundamentals of Computer Science I

Activity 13

Exploring how to simplify code using Boolean Operators.

Conditionals

All programs can be written without using any Boolean operators. By using them your code can be more simple and easy to read. In this activity you will explore how Boolean operators can simplify code.

  1. Fill in the following table. For each row of the table, write what the following function prints to the terminal window. Put the result in the column on the right.

    ExecuteResult
    def a_func(a, b):
        if a < b:
            is_a_less_than_b = True
        else:
            is_a_less_than_b = False
        return is_a_less_than_b
    print(a_func(1, 2))
    print(a_func(2, 1))
    print(a_func(1, 1))
    
    def a_func(a, b):
        return a < b
    print(a_func(1, 2))
    print(a_func(2, 1))
    print(a_func(1, 1))
    
    def a_func(a, b):
        is_a_less_than_b_and_0 = False
        if a < b:
            if a < 0:
                is_a_less_than_b_and_0 = True
        return is_a_less_than_b_and_0
    print(a_func(-2, -1))
    print(a_func(1, 2))
    print(a_func(2, 1))
    print(a_func(-1, -2))
    
    def a_func(a, b):
        return a < b and a < 0
    print(a_func(-2, -1))
    print(a_func(1, 2))
    print(a_func(2, 1))
    print(a_func(-1, -2))
    
    def a_func(a, b):
        is_a_less_than_b_or_0 = False
        if a < b:
            is_a_less_than_b_or_0 = True
        if a < 0:
            is_a_less_than_b_or_0 = True
        return is_a_less_than_b_or_0
    print(a_func(-2, -1))
    print(a_func(1, 2))
    print(a_func(2, 1))
    print(a_func(-1, -2))
    
    def a_func(a, b):
        return a < b or a < 0
    print(a_func(-2, -1))
    print(a_func(1, 2))
    print(a_func(2, 1))
    print(a_func(-1, -2))