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.
However, if we change the above and operator to or, we get the following:
The above expression prints True because the first value is a true value and the expression short circuits and does not evaluate child(). Conversely:
Let us look at more complex combinations of the and/or operators.
If you are still slightly confused, here is a handy cheatsheet!
What would the following statements evaluate to?
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))
Answers
False
True
"I hate Cake"
Last updated
Was this helpful?