Basics 2  booleans¶
Download exercises zip¶
PREREQUISITES:
Having read basics 1 integer variables
Booleans are used in boolean algebra and have the type bool
.
Values of truth in Python are represented with the keywords True
and False
: a boolean object can only have the values True
or False
.
[2]:
x = True
[3]:
x
[3]:
True
[4]:
type(x)
[4]:
bool
[5]:
y = False
[6]:
type(y)
[6]:
bool
Boolean operators¶
We can operate on boolean values with the operators not
, and
, or
:
and¶
a 
b 
a and b 













or¶
a 
b 
a or b 













not¶
a 
not a 





Questions with costants¶
QUESTION: For each of the following boolean expressions, try guessing the result (before guess, and then try them !):
not (True and False)
(not True) or (not (True or False))
not (not True)
not (True and (False or True))
not (not (not False))
True and (not (not((not False) and True)))
False or (False or ((True and True) and (True and False)))
Questions with variables¶
QUESTION: For each of these expressions, for which values of x
and y
they give True
? Try to think an answer before trying!
NOTE: there can be many combinations that produce True
, find them all
x or (not x)
(not x) and (not y)
x and (y or y)
x and (not y)
(not x) or y
y or not (y and x)
x and ((not x) or not(y))
(not (not x)) and not (x and y)
x and (x or (not(x) or not(not(x or not (x)))))
QUESTION: For each of these expressions, for which values of x
, y
and z
they give False
?
NOTE: there can be many combinations that produce False
, find them all
x or ((not y) or z)
x or (not y) or (not z)
not (x and y and (not z))
not (x and (not y) and (x or z))
y or ((x or y) and (not z))
De Morgan¶
There are a couple of laws that sometimes are useful:
Formula 
Equivalent to 





QUESTION: Look at following expressions, and try to rewrite them in equivalent ones by using De Morgan laws, simplifying the result wherever possible. Then verify the translation produces the same result as the original for all possible values of x
and y
.
(not x) or y
(not x) and (not y)
(not x) and (not (x or y))
Example:
x,y = False, False
#x,y = False, True
#x,y = True, False
#x,y = True, True
orig = x or y
trans = not((not x) and (not y))
print('orig=',orig)
print('trans=',trans)
[7]:
# verify here
Conversion¶
We can convert booleans into intergers with the predefined function int
. Each integer can be converted into a boolean (and vice versa) with bool
:
[8]:
bool(1)
[8]:
True
[9]:
bool(0)
[9]:
False
[10]:
bool(72)
[10]:
True
[11]:
bool(5)
[11]:
True
[12]:
int(True)
[12]:
1
[13]:
int(False)
[13]:
0
Each integer is valued to True
except 0
. Note that truth values True
and False
behave respectively like integers 1
and 0
.
Questions  what is a boolean?¶
QUESTION: For each of these expressions, which results it produces?
bool(True)
bool(False)
bool(2 + 4)
bool(431)
int(431)
True + True
True + False
True  True
True * True
Evaluation order¶
For efficiency reasons, during the evaluation of a boolean expression if Python discovers the possible result can only be one, it then avoids to calculate further expressions. For example, in this expression:
False and x
by reading from left to right, in the moment we encounter False
we already know that the result of and
operation will always be False
independetly from the value of x
(convince yourself).
Instead, if while reading from left to right Python finds first True
, it will continue the evaluation of following expressions and as result of the whole ``and`` will return the evaluation of the *last* expression_. If we are using booleans, we will not notice the differences, but by exchanging types we might get surprises:
[14]:
True and 5
[14]:
5
[15]:
5 and True
[15]:
True
[16]:
False and 5
[16]:
False
[17]:
5 and False
[17]:
False
Let’s think which order of evaluation Python might use for the or
operator. Have a look at the expression:
True or x
By reading from left to right, as soon as we find the True
we mich conclude that the result of the whole or
must be True
independently from the value of x
(convince yourself).
Instead, if the first value is False
, Python will continue in the evaluation until it finds a logical value True
, when this happens that value will be the result of the whole expression. We can notice it if we use different costants from True
and False
:
[18]:
False or 5
[18]:
5
[19]:
7 or False
[19]:
7
[20]:
3 or True
[20]:
3
The numbers you see have always a logical result coherent with the operations we did, that is, if you see 0
the expression result is intended to have logical value False
and if you see a number different from 0
the result is intended to be True
(convince yourself).
QUESTION: Have a look at the following expressions, and for each of them try to guess which result it produces (or if it gives an error):
0 and True
1 and 0
True and 1
0 and False
0 or False
0 or 1
False or 6
0 or True
Evaluation errors¶
What happens if a boolean expression contains some code that would generate an error? According to intuition, the program should terminate, but it’s not always like this.
Let’s try to generate an error on purpose. During math lessons they surely told you many times that dividing a number by zero is an error because the result is not defined. So if we try to ask Python what the result of 1/0
is we will (predictably) get complaints:
print(1/0)
print('after')

ZeroDivisionError Traceback (most recent call last)
<ipythoninput519e1622b385b6> in <module>()
> 1 1/0
ZeroDivisionError: division by zero
Notice that 'after'
is not printed because the progam gets first interrupted.
What if we try to write like this?
[21]:
False and 1/0
[21]:
False
Python produces a result without complaining ! Why? Evaluating form left to right it found a False
and so it concluded before hand that the expression result must be False
. Many times you will not be aware of these potential problems but it is good to understand them because there are indeed situations in which you can event exploit the execution order to prevent errors (for example in if
and while
instructions we will see later in the book).
QUESTION: Look at the following expression, and for each of them try to guess which result it produces (or if it gives on error):
True and 1/0
1/0 and 1/0
False or 1/0
True or 1/0
1/0 or True
1/0 or 1/0
True or (1/0 and True)
(not False) or not 1/0
True and 1/0 and True
(not True) or 1/0 or True
True and (not True) and 1/0
Comparison operators¶
Comparison operators allow to build expressions which return a boolean value:
Comparator 
Description 













[22]:
3 == 3
[22]:
True
[23]:
3 == 5
[23]:
False
[24]:
a,b = 3,5
[25]:
a == a
[25]:
True
[26]:
a == b
[26]:
False
[27]:
a == b  2
[27]:
True
[28]:
3 != 5 # 3 is different from 5 ?
[28]:
True
[29]:
3 != 3 # 3 is different from 3 ?
[29]:
False
[30]:
3 < 5
[30]:
True
[31]:
5 < 5
[31]:
False
[32]:
5 <= 5
[32]:
True
[33]:
8 > 5
[33]:
True
[34]:
8 > 8
[34]:
False
[35]:
8 >= 8
[35]:
True
Since the comparison are expressions which produce booleans, we can also assign the result to a variable:
[36]:
x = 5 > 3
[37]:
print(x)
True
QUESTION: Look at the following expression, and for each of them try to guess which result it produces (or if it gives on error):
x = 3 == 4 print(x)
x = False or True print(x)
True or False = x or False print(x)
x,y = 9,10 z = x < y and x == 3**2 print(z)
a,b = 7,6 a = b x = a >= b + 1 print(x)
x = 3^2 y = 9 print(x == y)
Exercise  The Lava Temple¶
During your studies you discover a map of an ancient temple, which hides marvelous treasures.
The temple measures d=80
meters each side, and is a labyrinth of corridors. You know for sure that some areas shown in red contain a fragile floor under which rivers of boiling lava are flowing: to warn about the danger while you’re walking, you build a detector which will emit a sound whenever you enter red zones.
Write a boolean expression which gives back True
if you are in a danger zone, and False
otherwise.
DO NOT use
if
instructions
[38]:
d = 80
x,y = 0, 0 # False
#x,y = 20, 20 # False
#x,y = 60, 10 # True
#x,y = 10, 60 # True
#x,y = 20, 70 # False
#x,y = 70, 20 # False
#x,y = 70, 70 # False
#x,y = 0,60 # True
#x,y = 60,0 # True
# write here
[38]:
False
Exercise  The Tower of Gradius I¶
The hands of the clock on the first Gradius Tower has rotated so far of n
degrees. Write some code which shows True
if the hand is in the zones in evidence, False
otherwise.
DO NOT use
if
instructionsn
can be greater than360
There two ways to solve the problem:
simple: write a long expressions with several
and
andor
harder: can you write a single short expression without
and
noror
?
[39]:
n = 20 # False
#n = 405 # False
#n = 70 # False
#n = 100 # True
#n = 460 # True
#n = 225 # True
#n = 182 # False
#n = 253 # False
#n = 275 # False
#n = 205 # False
#n = 350 # True
#n = 925 # False
#n = 815 # True
#n = 92 # True
# write here
[39]:
False
Exercise  The Pipe Jump¶
An Italian plumber is looking at 3 pipes of height t1
, t2
and t3
, each having respectively 10
, 20
and 30
coins above. Enthusiast, he makes a jump and reaches a height of h
. Write some code which prints the number of coins taken (10
,20
or 30
).
DO NOT use
if
instructionsHINT: If you don’t know how to do it, check again the paragraph Evaluation order and try thinking how to produce numbers when only a certain condition is true …
[40]:
t1,t2,t3 = 200,500,600
h=450 # 10
#h=570 # 20
#h=610 # 30
#h=50 # 0
# write here
[40]:
10
Exercise  The Tower of Gradius II¶
The hands of the clock on the second Gradius Tower have rotated so far of n
and m
degrees. Write some code which shows True
if both hands are in the same zone among the highlighted ones, False
otherwise.
DO NOT use
if
instructionsn
andm
can be greater than360
[41]:
n,m = 160,170 # True
#n,m = 135, 140 # False
#n,m = 160,190 # False
#n,m = 70,170 # False
#n,m = 350,260 # False
#n,m = 350,340 # True
#n,m = 350,340 # True
#n,m = 430,530 # False
#n,m = 520,510 # True
#n,m = 730,740 # False
# write here
[41]:
True
Continue¶
Go on with Basics 3  float numbers