Python Booleans: Basics - Exercises

Welcome to the exercises for Python Boolean Basics! These exercises will help you reinforce the concepts we covered in the lecture and build a solid foundation for working with Boolean logic in Python.

Instructions: Complete each exercise in a Python environment (IDE, notebook, or interpreter). Try to solve the exercises on your own before looking at the solutions.

Exercise 1: Boolean Basics

Let's start with some basic exercises to understand Boolean values and expressions.

# 1.1 Create two Boolean variables: one set to True and another set to False

# 1.2 Print the type of each variable

# 1.3 Convert the Boolean values to integers and print the result

# 1.4 Convert the integers 0 and 1 to Boolean values and print the result

# 1.5 Calculate the arithmetic sum of True + True + False and print the result

# 1.6 Calculate True * 5 and False * 5 and print the results

Expected Output:

<class 'bool'>
<class 'bool'>
1
0
True
False
2
5
0
Click for Solution
# 1.1 Create two Boolean variables: one set to True and another set to False
is_active = True
is_completed = False

# 1.2 Print the type of each variable
print(type(is_active))
print(type(is_completed))

# 1.3 Convert the Boolean values to integers and print the result
print(int(is_active))
print(int(is_completed))

# 1.4 Convert the integers 0 and 1 to Boolean values and print the result
print(bool(1))
print(bool(0))

# 1.5 Calculate the arithmetic sum of True + True + False and print the result
print(True + True + False)

# 1.6 Calculate True * 5 and False * 5 and print the results
print(True * 5)
print(False * 5)

Exercise 2: Boolean Operators

Now let's practice using Boolean operators: and, or, and not.

# 2.1 Create a function that checks if a number is both even and positive
def is_even_and_positive(number):
    # Your code here
    pass

# Test it with these values
print(is_even_and_positive(4))   # Should return True
print(is_even_and_positive(-2))  # Should return False
print(is_even_and_positive(7))   # Should return False

# 2.2 Create a function that checks if a string is empty or contains only whitespace
def is_empty_or_whitespace(text):
    # Your code here
    pass

# Test it with these values
print(is_empty_or_whitespace(""))        # Should return True
print(is_empty_or_whitespace("   "))     # Should return True
print(is_empty_or_whitespace("Hello"))   # Should return False

# 2.3 Create a function to implement a logical exclusive OR (XOR)
# XOR returns True if exactly one of the inputs is True, False otherwise
def xor(a, b):
    # Your code here
    pass

# Test it with all combinations
print(xor(True, True))    # Should return False
print(xor(True, False))   # Should return True
print(xor(False, True))   # Should return True
print(xor(False, False))  # Should return False

Expected Output:

True
False
False
True
True
False
False
True
True
False
Click for Solution
# 2.1 Create a function that checks if a number is both even and positive
def is_even_and_positive(number):
    return number > 0 and number % 2 == 0

# Test it with these values
print(is_even_and_positive(4))   # True
print(is_even_and_positive(-2))  # False
print(is_even_and_positive(7))   # False

# 2.2 Create a function that checks if a string is empty or contains only whitespace
def is_empty_or_whitespace(text):
    return text == "" or text.isspace()

# Test it with these values
print(is_empty_or_whitespace(""))        # True
print(is_empty_or_whitespace("   "))     # True
print(is_empty_or_whitespace("Hello"))   # False

# 2.3 Create a function to implement a logical exclusive OR (XOR)
# XOR returns True if exactly one of the inputs is True, False otherwise
def xor(a, b):
    # Option 1: Using Boolean operators
    return (a or b) and not (a and b)
    
    # Option 2: Using comparison operator
    # return a != b
    
    # Option 3: Using arithmetic
    # return (a + b) == 1

# Test it with all combinations
print(xor(True, True))    # False
print(xor(True, False))   # True
print(xor(False, True))   # True
print(xor(False, False))  # False

Exercise 3: Short-Circuit Evaluation

Let's explore short-circuit evaluation with a practical example.

# 3.1 Create a function that counts how many times it's called
call_count = 0

def count_call():
    global call_count
    call_count += 1
    return True

# Reset the counter
call_count = 0

# 3.2 Use the count_call function in an 'and' expression with False as the first operand
# Write your expression here

# Print the call count
print(f"Function called {call_count} times")  # Should be 0

# Reset the counter
call_count = 0

# 3.3 Use the count_call function in an 'and' expression with True as the first operand
# Write your expression here

# Print the call count
print(f"Function called {call_count} times")  # Should be 1

# 3.4 Create a function that handles division safely with short-circuit evaluation
def safe_divide(numerator, denominator):
    # Use short-circuit evaluation to check for zero denominator
    # Your code here
    pass

# Test it with various inputs
print(safe_divide(10, 2))   # Should return 5.0
print(safe_divide(10, 0))   # Should return "Cannot divide by zero"

Expected Output:

Function called 0 times
Function called 1 times
5.0
Cannot divide by zero
Click for Solution
# 3.1 Create a function that counts how many times it's called
call_count = 0

def count_call():
    global call_count
    call_count += 1
    return True

# Reset the counter
call_count = 0

# 3.2 Use the count_call function in an 'and' expression with False as the first operand
result = False and count_call()

# Print the call count
print(f"Function called {call_count} times")  # 0 - Short-circuit prevented the call

# Reset the counter
call_count = 0

# 3.3 Use the count_call function in an 'and' expression with True as the first operand
result = True and count_call()

# Print the call count
print(f"Function called {call_count} times")  # 1 - Function was called

# 3.4 Create a function that handles division safely with short-circuit evaluation
def safe_divide(numerator, denominator):
    # Use short-circuit evaluation to check for zero denominator
    return "Cannot divide by zero" if denominator == 0 else numerator / denominator
    
    # Alternative with and/or:
    # return denominator != 0 and numerator / denominator or "Cannot divide by zero"

# Test it with various inputs
print(safe_divide(10, 2))   # 5.0
print(safe_divide(10, 0))   # Cannot divide by zero

Exercise 4: Truth Value Testing

Let's practice with truth value testing and truthy/falsy values.

# 4.1 Create a function that returns a descriptive message about the truth value of an object
def describe_truth_value(value):
    # Your code here
    pass

# Test it with various values
print(describe_truth_value(0))          # Should say "Falsy"
print(describe_truth_value(42))         # Should say "Truthy"
print(describe_truth_value(""))         # Should say "Falsy"
print(describe_truth_value("Hello"))    # Should say "Truthy"
print(describe_truth_value([]))         # Should say "Falsy"
print(describe_truth_value([1, 2, 3]))  # Should say "Truthy"
print(describe_truth_value(None))       # Should say "Falsy"

# 4.2 Create a function that validates user input
def validate_input(user_input):
    """
    Validate that user input is not empty and contains more than just whitespace.
    Return True if valid, False otherwise.
    """
    # Your code here
    pass

# Test it with various inputs
print(validate_input("John Doe"))   # Should return True
print(validate_input(""))           # Should return False
print(validate_input("   "))        # Should return False

# 4.3 Create a function that returns either the input value or a default value
def get_value_or_default(value, default="Default Value"):
    """
    Return the input value if it's truthy, otherwise return the default value.
    """
    # Your code here
    pass

# Test it with various inputs
print(get_value_or_default("Hello"))       # Should return "Hello"
print(get_value_or_default(""))            # Should return "Default Value"
print(get_value_or_default(0, "Zero"))     # Should return "Zero"
print(get_value_or_default(None, "N/A"))   # Should return "N/A"

Expected Output:

0 is Falsy
42 is Truthy
'' is Falsy
Hello is Truthy
[] is Falsy
[1, 2, 3] is Truthy
None is Falsy
True
False
False
Hello
Default Value
Zero
N/A
Click for Solution
# 4.1 Create a function that returns a descriptive message about the truth value of an object
def describe_truth_value(value):
    if value:
        return f"{value} is Truthy"
    else:
        return f"{repr(value)} is Falsy"

# Test it with various values
print(describe_truth_value(0))          # 0 is Falsy
print(describe_truth_value(42))         # 42 is Truthy
print(describe_truth_value(""))         # '' is Falsy
print(describe_truth_value("Hello"))    # Hello is Truthy
print(describe_truth_value([]))         # [] is Falsy
print(describe_truth_value([1, 2, 3]))  # [1, 2, 3] is Truthy
print(describe_truth_value(None))       # None is Falsy

# 4.2 Create a function that validates user input
def validate_input(user_input):
    """
    Validate that user input is not empty and contains more than just whitespace.
    Return True if valid, False otherwise.
    """
    # Option 1: Explicit check
    # return user_input != "" and not user_input.isspace()
    
    # Option 2: After stripping whitespace, check if anything remains
    return bool(user_input.strip())

# Test it with various inputs
print(validate_input("John Doe"))   # True
print(validate_input(""))           # False
print(validate_input("   "))        # False

# 4.3 Create a function that returns either the input value or a default value
def get_value_or_default(value, default="Default Value"):
    """
    Return the input value if it's truthy, otherwise return the default value.
    """
    # Option 1: Using if-else
    # if value:
    #     return value
    # else:
    #     return default
    
    # Option 2: Using boolean operators (more Pythonic)
    return value or default

# Test it with various inputs
print(get_value_or_default("Hello"))       # "Hello"
print(get_value_or_default(""))            # "Default Value"
print(get_value_or_default(0, "Zero"))     # "Zero"
print(get_value_or_default(None, "N/A"))   # "N/A"

Exercise 5: Challenge Exercise - Login System

Let's create a simple login system that uses Boolean logic for validation.

# 5.1 Create a simple user database as a dictionary
users = {
    "alice": {"password": "securepass123", "role": "admin"},
    "bob": {"password": "bobpass456", "role": "user"},
    "charlie": {"password": "charlie789", "role": "user"}
}

# 5.2 Create a function to validate login credentials
def validate_login(username, password):
    """
    Check if the username exists and the password is correct.
    Return a tuple (success, message)
    """
    # Your code here
    pass

# Test the login function
print(validate_login("alice", "securepass123"))  # Should return (True, "Login successful")
print(validate_login("alice", "wrongpass"))      # Should return (False, "Incorrect password")
print(validate_login("eve", "evepass"))          # Should return (False, "Username not found")

# 5.3 Create a function to check if a user has admin privileges
def check_admin_access(username, password):
    """
    Return True if the user exists, the password is correct, 
    and the user has admin role. Otherwise, return False.
    """
    # Your code here
    pass

# Test the admin check function
print(check_admin_access("alice", "securepass123"))  # Should return True
print(check_admin_access("bob", "bobpass456"))       # Should return False
print(check_admin_access("alice", "wrongpass"))      # Should return False

Expected Output:

(True, 'Login successful')
(False, 'Incorrect password')
(False, 'Username not found')
True
False
False
Click for Solution
# 5.1 Create a simple user database as a dictionary
users = {
    "alice": {"password": "securepass123", "role": "admin"},
    "bob": {"password": "bobpass456", "role": "user"},
    "charlie": {"password": "charlie789", "role": "user"}
}

# 5.2 Create a function to validate login credentials
def validate_login(username, password):
    """
    Check if the username exists and the password is correct.
    Return a tuple (success, message)
    """
    # Check if username exists
    if username not in users:
        return (False, "Username not found")
    
    # Check if password is correct
    if users[username]["password"] == password:
        return (True, "Login successful")
    else:
        return (False, "Incorrect password")

# Test the login function
print(validate_login("alice", "securepass123"))  # (True, "Login successful")
print(validate_login("alice", "wrongpass"))      # (False, "Incorrect password")
print(validate_login("eve", "evepass"))          # (False, "Username not found")

# 5.3 Create a function to check if a user has admin privileges
def check_admin_access(username, password):
    """
    Return True if the user exists, the password is correct, 
    and the user has admin role. Otherwise, return False.
    """
    # Using logical AND to check all conditions
    return (username in users and 
            users[username]["password"] == password and 
            users[username]["role"] == "admin")
    
    # Alternative approach using validate_login first:
    # login_success, _ = validate_login(username, password)
    # return login_success and users[username]["role"] == "admin"

# Test the admin check function
print(check_admin_access("alice", "securepass123"))  # True
print(check_admin_access("bob", "bobpass456"))       # False
print(check_admin_access("alice", "wrongpass"))      # False

Bonus Challenge: Boolean Logic Evaluator

Create a function that takes a string representing a Boolean expression and evaluates it. The expression will contain only True, False, and, or, not, and parentheses.

def evaluate_boolean_expression(expression):
    """
    Evaluate a string representing a Boolean expression.
    Example: "True and (False or not False)"
    Should return True
    
    Note: For simplicity, assume proper spacing between terms.
    """
    # Your code here (Hint: you might want to use 'eval' with caution)
    pass

# Test the function
print(evaluate_boolean_expression("True and True"))               # Should return True
print(evaluate_boolean_expression("True and False"))              # Should return False
print(evaluate_boolean_expression("False or True"))               # Should return True
print(evaluate_boolean_expression("not False"))                   # Should return True
print(evaluate_boolean_expression("not True"))                    # Should return False
print(evaluate_boolean_expression("True and (False or True)"))    # Should return True
print(evaluate_boolean_expression("(True and False) or True"))    # Should return True
print(evaluate_boolean_expression("not (True and True)"))         # Should return False

Expected Output:

True
False
True
True
False
True
True
False
Click for Solution
def evaluate_boolean_expression(expression):
    """
    Evaluate a string representing a Boolean expression.
    Example: "True and (False or not False)"
    Should return True
    
    Note: For simplicity, assume proper spacing between terms.
    """
    # Simple solution using eval (normally, be cautious with eval for security reasons)
    return eval(expression)
    
    # Alternative: A more complex but safer parser would implement a proper
    # tokenizer and parser for Boolean expressions, but that's beyond the scope
    # of this exercise.

# Test the function
print(evaluate_boolean_expression("True and True"))               # True
print(evaluate_boolean_expression("True and False"))              # False
print(evaluate_boolean_expression("False or True"))               # True
print(evaluate_boolean_expression("not False"))                   # True
print(evaluate_boolean_expression("not True"))                    # False
print(evaluate_boolean_expression("True and (False or True)"))    # True
print(evaluate_boolean_expression("(True and False) or True"))    # True
print(evaluate_boolean_expression("not (True and True)"))         # False

Next Steps

Congratulations on completing the exercises for Python Boolean Basics! These exercises have helped you practice:

Ready to Continue? The next lecture covers practical applications of Boolean logic in Python programming. You'll learn how to apply these fundamental concepts to solve real-world problems.

Continue to Boolean Applications Lecture

© 2025 RMdelapaz All rights reserved.