Control Flow: The if, elif, else Statements

Truth Table

Example values for boolean variables or function calls

a = True, b = False, c= True

a or b and c : True

b or a and not c : False

(b or a) and not c : False


Precedence in boolean statements

The order of precedence in boolean statements higher to lower precedence is as follows:

"()", "not", "and", and "or".

a b a and b a or b not a or b not (a or b)
False False False False True True
False True False True True False
True False False True False False
True True True True True False

The logical expression (a or b or (c or not b and not (a or c)))  evaluates to True as shown step by step in the following solution

(a or b or (c or not b and not (True)))
(a or b or (c or not b and False))
(a or b or (c or False))
(a or b or True)
(True)

In fact, in most of the programming languages the boolean statements are evaluated from left to right. Adhering to the short-circuit evaluation principle, the Python interpreter will not evaluate the second operand of the or operator if the first operand is evaluated to True. Similarly, the second operand of an and operator will not be evaluated if the first operand is evaluated to False. However, the remaining statements may be evaluated depending on the structure of the compound statement.

a or b or (c or not b and not (a or c))
True or b or (c or not b and not (a or c)) 

will evaluate directly to True since the value of a is True and the rest of the expression (b or (c or not b and not (a or c))) is not going to be checked. On the other hand, the statement a or True or b  will first check for the value of a although there is an explicitly stated True value in the expression constructed of or operators only.

A simple test using a function with a boolean return value instead of a variable is provided below. It can be executed to test the short-circuit evaluation principle by replacing or with and, inserting additional or and and operators, modifying the return value of the function, or adding extra functions, etc.:

def getValue():
    print("called getValue function, you may include code that operates on databases, accesses network, stores data, etc. before returning the result value")
    result = False
    return result


print(getValue() or True or getValue())

DeMorgan's Law

When applying the negation operator not to the compound logical statements, the well known DeMorgan's law applies as

not (a or b) is equal to: not a and not b

and

not (a and b) is equal to: not a or not b