Boolean arithmetic

We can operate on Boolean values:

In [1]:
(True and True) == True                 #a and b: a is True and b is True
Out[1]:
True
In [2]:
((True and False) == False ) == False   #The value of the whole expression
                                        #is False, since (True and False) == False 
Out[2]:
False
In [3]:
(True or False) == True                 #a or b: at least one of a or b is true
                                        #The whole expression is True in this case
Out[3]:
True
In [6]:
(True or True) == True                  #The value of the expression is True
Out[6]:
True
In [7]:
not True
Out[7]:
False
In [8]:
not False
Out[8]:
True
In [9]:
not (True or False)
Out[9]:
False

Note: the Boolean "or" isn't quite the same as the English "or". "For dessert, I'll have pie or I'll have ice cream" in English means that I'll only have one dessert. In Python, it means that I'll have at least one dessert (since it means that one of "I'll have pie" or "I'll have ice cream" is true)

P1: Exclusive or

How do you express the English "I'll have pie or I'll have ice cream?" Define two Boolean variables:

In [5]:
will_have_pie = False
will_have_ice_cream = True

print "Reasonable amount of dessert" the variables satisfy the English "For dessert, I'll have pie or I'll have ice cream"

P1: Solution

In [11]:
if (will_have_pie and not will_have_ice_cream) or (not will_have_pie and will_have_ice_cream):
    print("Reasonable amount of dessert")
else:
    print("Unreasonable amount of dessert")
Reasonable amount of dessert