Short Circuiting

This section continues with the idea of short circuiting using boolean operators introduced in Module 4.

evaluate_and = True and False #returns False
#The statement below returns False, but does not evaluate the last True value. 
evaluate_and2 = True and False and True 

How would this look in practice?

have_pb = True
have_jelly = True 
have_bread = True 
have_butter = False
have_mayo = False

#This is a function in Python. You do not have to know what it is or how to write one. 
#For the sake of this exercise only, we will be using it to simulate a child asking
#asking for a sandwich. 
def child():
    return "I want a sandwich"
######

if (have_pb and have_jelly and have_bread):
    print("Make a PB and J sandwich")

The statement above will always print because all the variables have true values.

if (have_bread and have_butter and have_mayo):
    print("Here is a basic sandwich")
else: 
    print("I'm sad")
#The statement above will always print I'm sad, because have_butter and have_mayo are 
#false values. 

However, if we change the above and operator to or, we get the following:

if (have_bread or have_butter or have_mayo):
    print("I have bread")
else: 
    print("I'm sad")
#This will always print I have bread, because there is one true value (have_bread).
print(have_bread or child()) 

The above expression prints True because the first value is a true value and the expression short circuits and does not evaluate child(). Conversely:

print(have_butter or child())
#This prints "I want a sandwich" because a the operator evaluated until the first true
#statement because have_butter is false. 
print(have_pb and have_bread and have_butter and child())
#This prints False because the expression short-circuits and child() is not evaluated.

Let us look at more complex combinations of the and/or operators.

print((have_butter and have_bread) or child())
#This prints "I want a sandwich" because the and statement evaluates to False
#The or statement evaluates to child()

print((have_butter or have_bread or child()) and (have_butter or have_mayo))
#This will evaluate to False because the first expression evaluates to True and 
#the second to false because there is no true value. When joined by an and operator, 
#it becomes print(True and False), which we know prints False. 

If you are still slightly confused, here is a handy cheatsheet!

What would the following statements evaluate to?

def adult():
    return "I hate cake"
have_cupcake = True
have_icecream = False
have_cakepop = True
have_soda = False
  1. print(have_cupcake and have_icecream and adult())

  2. print(have_icecream or adult() or have_cupcake())

  3. print((have_cakepop and adult()) or (adult() and have_icecream))

Last updated