This section continues with the idea of short circuiting using boolean operators introduced in Module 4.
evaluate_and =TrueandFalse#returns False#The statement below returns False, but does not evaluate the last True value. evaluate_and2 =TrueandFalseandTrue
How would this look in practice?
have_pb =Truehave_jelly =Truehave_bread =Truehave_butter =Falsehave_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. defchild():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 orchild())
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 orchild())#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 andchild())#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) orchild())#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 orchild()) 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?
defadult():return"I hate cake"have_cupcake =Truehave_icecream =Falsehave_cakepop =Truehave_soda =False
print(have_cupcake and have_icecream and adult())
print(have_icecream or adult() or have_cupcake())
print((have_cakepop and adult()) or (adult() and have_icecream))