Table of Content
Python has two values of the bool
type, written True
and False
. These are called logical values
or Boolean values, named after 19th century mathematician George Boole.
True # show the value
type(True) # check the type name
False # show the value
type(False) # check the type name
true
false
We have seen arithmetic operators that produce as output numerical values. Today, we'll see relational operators that
produce as output Boolean values. Relational operators are used to compare two values.
Below try to first guess the values before running the cell.
3 < 5
3 < 2
3 > 2
5 == 5
5 >= 5
6 <= 5
Note: ==
is pronounced "equals" and !=
is pronounced "not equals". This is why we distinguish the pronunciation
of the single equal sign = as "gets", which is assignment and nothing to do with mathematical equality!
Relational operators can also be used to compare strings, in dictionary order. This means, the way words are ordered in a dictionary. Words that occur toward the start of a dictionary, are deemed "smaller" than words that occur toward the middle or end.
'bat' < 'cat'
'bat' < 'ant'
'bat' == 'bat'
'bat' < 'bath'
'Cat' < 'bat'
EXPLANATION: How does this comparison of string values work? Python starts by comparing the first character of each string to one another. For example "b" with "c". Because the computer doesn't know anything about letters, it converts everything into numbers. Each character has a numerical code that is summarized in this table of ASCII codes. In Python, we can look up the ASCII code via the Python built-in function ord
:
print("a", ord('a'))
print("b", ord('b'))
print("c", ord('c'))
As you can see, the value for 'b', 98, is smaller than the value for 'c', 99, thus, 'b' < 'c'
. Once two unequal characters are found, Python stops comparing the other characters, because there is no point in continuing. However, if characters are the same, like in 'bat' and 'bath', the comparisons continue until the point in which something that differs is found. In this case, there is an extra 't', making 'bath' greater in value than 'bat'.
Uppercase vs. Lowercase: Counterintuitively, it turns out, the upppercase letters are internally represented with smaller numbers than lowercase letters. See the ASCII table and the examples below:
print("A", "is", ord('A'))
print("a", "is", ord('a'))
print("B", "is", ord('B'))
print("b", "is", ord('b'))
This explains why the world 'Cat' is smaller than the word 'cat'.
There are three logical operators: not
, and
, or
, which are applied on expressions that are already evaluated as boolean values.
not
¶not expression evaluates to the opposite of the truth value of expression
not (3 > 5) # parentheses not necessary - relational operators have higher precedence
not (3 == 3)
and
¶exp1 and exp2 evaluates to True
iff both exp1 and exp2 evaluate to True
.
True and True
True and False
(3 < 5) and ('bat' < 'ant')
(3 < 5) and ('bat' < 'cat')
or
¶exp1 or exp2 evaluates to True
iff at least one of exp1 and exp2 evaluate to True
.
True or True
True or False
(3 > 5) or ('bat' < 'cat')
(3 > 5) or ('bat' < 'ant')
You can assign booleans to variables just like any other value. The variables below represent whether someone likes particular genres of music.
Note: Try to guess each expression before running the code.
# change these as you like to experiment
pop = False
rap = True
hiphop = True
not pop
pop and rap
rap and hiphop
pop or hiphop
hiphop or rap
What are the order of operations here? Do we compute the operator and
first or or
?
rap or hiphop and pop
and takes precendence over or, so the above expression is the same as
rap or (hiphop and pop)
but not the same as
(rap or hiphop) and pop
Note: While rap or hiphop and pop
and rap or (hiphop and pop)
in the examples above are equivalent, that doesn't nesserarily mean that Pythohn evaluates first the and
operation. If rap
is True, the rest of the expression is never executed, because it doesn't matter. When one operand is True, the result of an OR operation is always TRUE. Only if the operand is False, will Python continue evaluating the second operand of the OR expression.
def doILikeMissyElliott(rap, hiphop, pop):
"""determine if I like Missy Elliott."""
return rap or hiphop and pop
doILikeMissyElliott(False, True, True)
doILikeMissyElliott(True, True, False)
doILikeMissyElliott(False, False, True)
Usually, the function body will contain a complex expression combining relational and logical expressions, as the following examples show:
def isFaculty(name):
"""determine if the name belong to a CS 111 faculty member."""
return (name == 'Eni' or name == 'Carolyn'
or name == 'Andy' or name == 'Lyn'
or name == 'Sohie' or name == 'Peter')
isFaculty('Carolyn')
isFaculty("andy")
Note: Explain the result of the last cell. Is that what you expected?
Expressing intervals of numbers: We can combine relational expressions to create intervals of numbers that fulfill certain criteria. Below is a predicate that checks if a value is within a given interval of numbers.
def isBetween(n, lo, hi):
"""determines if n is between lo and hi"""
return (lo <= n) and (n <= hi)
More fun with Math: Is a number divisible by a factor? Is it even?
def isDivisibleBy(num, factor):
"""determines if num is divisible by factor"""
return (num % factor) == 0 # notice the remainder operator
def isEven(n):
"""determines if n is even"""
return isDivisibleBy(n, 2)
print('Is 3774 divisible by 11?', isDivisibleBy(3774, 11))
print('Is 473 even?', isEven(473))
Is n a prime integer less than 100? In the solution below, notice how we split the long expression across mutliple lines for readability, and wrap all multiline expressions in parentheses.
# Version with continuation characters for multiline expressions
def isSmallPrime(n):
return (isinstance(n, int) # is n an integer?
and (n > 1) and (n < 100) # is n between 1 and 100?
and (n==2 or n==3 or n==5 or n==7 # is n 2, 3, 5, or 7?
or not (isDivisibleBy(n,2) #is n divisible by 2, 3, 5, or 7?
or isDivisibleBy(n,3)
or isDivisibleBy(n,5)
or isDivisibleBy(n,7))))
isSmallPrime(23)
isSmallPrime(42)
When multiline expressions are not wrapped in parentheses, you must use the special continuation character \ at the end of each line. No character other than a newline can come after the \.
# Version with continuation characters for some multiline expressions
def isSmallPrime(n):
return isinstance(n, int) \
and (n > 1) and (n < 100) \
and (n==2 or n==3 or n==5 or n==7 # No need for \ because of open parentheses
or not (isDivisibleBy(n,2)
or isDivisibleBy(n,3)
or isDivisibleBy(n,5)
or isDivisibleBy(n,7)))
The version below is an alternative solutions that uses De Morgan's laws.
# alternate version using De Morgan's laws
def isSmallPrime2(n):
return (isinstance(n, int)
and (n > 1) and (n < 100) # is n between 1 and 100?
and (n==2 or n==3 or n==5 or n==7 # is n 2, 3, 5, or 7?
or (not isDivisibleBy(n,2) #is n divisible by 2, 3, 5, or 7?
and not isDivisibleBy(n,3)
and not isDivisibleBy(n,5)
and not isDivisibleBy(n,7))))
Write the following four predicates.
Remember: a predicate is simply a function that returns a Boolean value.
isFreezing
: is the temperature in Fahrenheit at or below freezing?
isLongName
: is a name longer than 20 characters?
isVowel
: is a character a vowel?
startsWithVowel
: does a string start with a vowel?
Do not use conditional statements to solve these problems. Only relational or logical expressions!
isFreezing
¶# Your code here
def isFreezing(temp):
return temp <= 32
isFreezing(10)
isFreezing(75)
isLongName
¶# Your code here
def isLongName(name):
return len(name) > 20
isLongName('Wellesley')
isLongName('Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')
(Above is the name of a village in Wales; you can hear it pronounced in this video.)
isVowel
¶# There are multiple possible solutions for this problem
# Your code here
def isVowel(letter):
letterLower = letter.lower()
return (letterLower == 'a' or
letterLower == 'e' or
letterLower == 'i' or
letterLower == 'o' or
letterLower == 'u')
isVowel('e')
isVowel('U')
isVowel('b')
An alternative solution
There are many ways to write the function isVowel
. Here is another version, which doesn't make assumptions about the user's input to the function:
# Your code here
def isVowel(letter):
return len(letter) == 1 and letter.lower() in 'aeiou'
isVowel('a')
startsWithVowel
¶Note: if s is a string, s[0] returns the first character of s.
s = "Boston"
s[0]
# Your code here
def startsWithVowel(word):
return isVowel(word[0])
startsWithVowel('Esmeralda')
startsWithVowel('bravery')