Boolean Values¶

We already saw Boolean values in lecture:

In [1]:
True
Out[1]:
True
In [2]:
1 == 1
Out[2]:
True
In [3]:
1 > 200
Out[3]:
False

Those are values that can be either True or False.

In the same way that we can do algebra using integers:

In [4]:
1 + 1
Out[4]:
2

we can also do algebra using Boolean values:

In [5]:
a = False
a or (1 == 1)
Out[5]:
True

Here is how we can use and and or:

A and B:

(True and True)   == True
(True and False)  == False
(False and True)  == False
(False and False) == False

In English, A and B is True if and only if both A and B are True.

A or B:

(True or True)    == True
(True or False)   == True
(False or True)   == True
(False or False)  == False

In English, A or B is True if and only if at least one (or both) of A and B are True.

You can also use not

(not True)        == False
(not False)       == True

In English, the value of not A is the opposite of the value of A.

Note that the Python or and the English or are not quite the same. Consider the following English statement:

"For dessert, I'll have ice cream or pie"

This means that I'll have either ice cream or pie, but not both. This means that the following will not work in the way we'd expect from the English meaning of the quote.

In [6]:
ice_cream = True
pie = True
if pie or ice_cream:
    print("I didn't lie")
I didn't lie

The problem is that True or True is True, but we want the condition to be False if both ice_cream and pie are True if we want the condition implied by the English quote. Here are ways to achive what we actually want.

In [1]:
ice_cream = True
pie = False
if (pie == True and ice_cream == False) or (pie==False and ice_cream==True):
  print("I didn't lie")
  
if (pie and not ice_cream) or (not pie and ice_cream):
  print("I didn't lie")
I didn't lie
I didn't lie

There is actually a simpler solution: One of pie and ice_cream is True and the other False if and only if pie is not the same as ice_cream. So we could use:

In [2]:
if pie != ice_cream:
    print("I didn't lie")
I didn't lie

Operator Precedence¶

Here is another example:

In [8]:
lazy = False
smart = True
growthmindset = False

if not lazy and smart and growthmindset:
    print("Go to EngSci")
elif  lazy and smart:
    print("Go to Physics")
elif not lazy and smart and not growthmindset:
    print("Go to Economics")
else:
    print("Go to Ryerson")
Go to Economics

What does an expression like not lazy and smart and growthmindset mean? Every operator (like not, and, etc.) has a precedence, i.e., the operators are executed according to which has more precendence. This is just like in math (and in Python) 3 + 5 * 2 means 3 + (5 * 2), and a * b * c means (a * b) * c. When in doubt, use parentheses!