Python logical AND and OR operations with Boolean values
2. Boolean Operations
Write a Python function that takes two boolean values as input and returns the logical AND and OR of those values.
Sample Solution:
Code:
def logical_operations(x, y):
    logical_and = x and y
    logical_or = x or y
    return logical_and, logical_or
def main():
    try:
        inputval1 = input("Input first boolean value (True/False): ").lower()
        inputval2 = input("Input second boolean value (True/False): ").lower()
        if inputval1 == "true":
            bool1 = True
        elif inputval1 == "false":
            bool1 = False
        else:
            print("Invalid input for first boolean value.")
            return
        if inputval2 == "true":
            bool2 = True
        elif inputval2 == "false":
            bool2 = False
        else:
            print("Invalid input for second boolean value.")
            return
        logical_and, logical_or = logical_operations(bool1, bool2)
        print(f"Logical AND: {logical_and}")
        print(f"Logical OR: {logical_or}")
    except ValueError:
        print("Invalid input. Please input either 'True' or 'False'.")
if __name__ == "__main__":
    main()
Output:
Input first boolean value (True/False): FALSE Input second boolean value (True/False): TRUE Logical AND: False Logical OR: True
Input first boolean value (True/False): FALSE Input second boolean value (True/False): FALSE Logical AND: False Logical OR: False
Input first boolean value (True/False): TRUE Input second boolean value (True/False): TRUE Logical AND: True Logical OR: True
Input first boolean value (True/False): TRUE Input second boolean value (True/False): FALSE Logical AND: False Logical OR: True
The above exercise takes two boolean values as user input (either "True" or "False"), converts them to boolean variables, calculates their logical AND and OR using the "logical_operations()" function, and then prints the results.
Flowchart:
 
For more Practice: Solve these Related Problems:
- Write a Python function that takes two booleans and returns their AND, OR, and XOR results as a dictionary.
- Write a Python program to simulate logical operations on two boolean inputs, printing the results for NAND and NOR as well as AND and OR.
- Write a Python script to accept two boolean values from the user, compute the logical AND and OR, and output the results in a formatted string.
- Write a Python program to create a function that accepts two booleans and returns a tuple containing the results of AND, OR, and the negation of each using boolean operators.
Go to:
Previous: Check even or odd number using Boolean variables in Python.
Next: Voting eligibility checker.
Python Code Editor :
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
