Logical Operators - Exercises - SOLVED#

We’ll run through how to demonstrate a mathematical logical proof “de Morgan’s” law, using logical operators. We’ll do this by asking you to write a number of functions to compute logical operations, and then explore this law, and how to prove it:

Exercise#

Write a function, logical_1 that takes two inputs P and Q and returns the logical operation

\[ \mbox{not } (P \mbox{ or } Q) \]

NOTE: We provide the solution here for you to see an example. You’ll then have to do this yourself in the next exercise!

def logical_1(P, Q):
    return not (P or Q)

Test that your function works by calling it with the 4 possible inputs.

Again we give the solution: As P and Q are boolean, they each have two possible values; True or False. So we can only call it as follows:

print(logical_1(True, False))
print(logical_1(True, True))
print(logical_1(False, False))
print(logical_1(False, True))

print("\n\nThis should have read\nFalse\nFalse\nTrue\nFalse")
False
False
True
False


This should have read
False
False
True
False

Exercise#

Write a function, logical_2 that takes two inputs P and Q and returns the logical operation

\[ \quad (\mbox{not } P) \mbox{ and } (\mbox{not } Q)\]

Test this for the possible values of input values, same as above!

def logical_2(P, Q):
    """Returns (not P) and (not Q)"""
    return (not P) and (not Q)
print(logical_2(True, False))
print(logical_2(True, True))
print(logical_2(False, False))
print(logical_2(False, True))
False
False
True
False

Exercise#

One of de Morgan’s Laws states that

\[ \mbox{not } (P \mbox{ or } Q) \quad \textbf{ is equivalent to } \quad (\mbox{not } P) \mbox{ and } (\mbox{not } Q)\]

From your functions above, show that this is always true. HINT there is only 2 possible values of \(P\) and 2 possible values of \(Q\) so if this is True for all the 4 possible combinations, it is always true. The functions for the 2 exercises above should also be used directly here.

def eval_func(P, Q):
    return logical_1(P,Q) == logical_2(P,Q)
print(eval_func(True, True), eval_func(True, False), eval_func(False, True), eval_func(False, False))
True True True True

Exercise#

de Morgan’s other Law states that

\[ \mbox{not } (P \mbox{ and } Q) \quad \textbf{ is equivalent to } \quad (\mbox{not } P) \mbox{ or } (\mbox{not } Q)\]

Also demonstrate, following the same process as above, that this is always true.

def logical_3(P, Q):
    return not (P and Q)

def logical_4(P, Q):
    return (not P) or (not Q)

def eval_func2(P, Q):
    return logical_3(P,Q) == logical_4(P,Q)
print(eval_func2(True, True), eval_func2(True, False), eval_func2(False, True), eval_func2(False, False))
True True True True