Lec Booleans
Lec Booleans
and Predicates
Essentials of Python
Python has two values of bool type, written True and False.
These are called logical values or Boolean values, named after 19th
century mathematician George Boole.
The values must be capitalized.
Booleans 3
Concepts in this slide:
Relational Operators New operators: relational.
They are: >, <, ==, !=, >=, <=
Booleans most naturally arise in the context of relational operators
that compare two values.
In [1]: 3 < 5 In [5]: 5 >= 1
Out[1]: True Out[5]: True “equals”
Not
not a: the cake does not have pineapple True/False?
And
a and b: the cake has pineapple & the cake is chocolate True/False?
b and c: the cake is chocolate & the cake has walnuts True/False?
Logical
not a
operators are
a used in everyday
speech (see
Slide 6), but also
consistently in
Math and CS.
a and b
a b
a or b
a b
Booleans 7
Concepts in this slide:
Logical Operators: Logical operators work
with Boolean values or
not, and, or relational expressions.
def isEven(n):
"""determines whether n is even"""
return isDivisibleBy(n, 2)
def isHogwartsHouse(s):
return (s == 'Gryffindor' or s == 'Hufflepuff'
or s == 'Ravenclaw' or s == 'Slytherin’)
def isSmallPrime(n):
"""determines if n is a prime integer less than 100"""
return (isinstance(n, int)
and (n > 1) and (n < 100)
and (n == 2 or n == 3 or n == 5 or n == 7
or not (isDivisibleBy(n,2)
or isDivisibleBy(n,3)
or isDivisibleBy(n,5)
or isDivisibleBy(n,7))))
Booleans 11
Preview: Some useful string operations
We will cover strings and other “sequence” types like tuples and lists in a few
lectures, but here are some useful operations that come handy when writing
predicates.
The square bracket []operator can be used to index (access) an element of a string.
In [7]: isVowel('b')
Out[7]: False
In [9]: startsWithVowel('bravery')
Out[9]: False
Booleans 13
in and not in test for substrings
s1 in s2 tests if string s1 is a substring of string s2
Booleans 15
Combining logical operators
What cake do I like?
Booleans 16
Continuation Characters in Long Expressions
It is an annoying but important Python fact that if you want to write expressions
without parens that span multiple lines, you must use the backslash continuation
character to end each line (and this character cannot be followed by any other character
except newline). Furthermore such multiline expressions cannot contain embedded
comments, such as # Is n an integer?
def isHogwartsHouse(s):
return s == 'Gryffindor' or s == 'Hufflepuff' \
or s == 'Ravenclaw' or s == 'Slytherin'
Booleans 20