0% found this document useful (0 votes)
22 views20 pages

Lec Booleans

The document discusses Booleans, logical expressions, and predicates in Python. Some key points: - Python has two Boolean values, True and False, which arise from comparing values with relational operators like ==, !=, <, >, etc. - Logical operators like and, or, and not allow combining Boolean expressions to form more complex conditional logic. - A predicate is any function that returns a Boolean value, allowing conditional logic to be encapsulated for reuse. Examples of predicates test properties like divisibility, string length matching, etc. - Truth tables define the output of the and, or, and not operators for all combinations of True and False inputs. So in summary

Uploaded by

ayush agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views20 pages

Lec Booleans

The document discusses Booleans, logical expressions, and predicates in Python. Some key points: - Python has two Boolean values, True and False, which arise from comparing values with relational operators like ==, !=, <, >, etc. - Logical operators like and, or, and not allow combining Boolean expressions to form more complex conditional logic. - A predicate is any function that returns a Boolean value, allowing conditional logic to be encapsulated for reuse. Examples of predicates test properties like divisibility, string length matching, etc. - Truth tables define the output of the and, or, and not operators for all combinations of True and False inputs. So in summary

Uploaded by

ayush agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Booleans, Logical Expressions,

and Predicates

Essentials of Python

By: Ayush Agarwal


Concepts in this slide:
Real-life examples for
Making Decisions decision making with
Boolean values.

If it’s raining then bring umbrella and wear boots.

If timer is up, then do not cross True or False? Booleans 2


Concepts in this slide:
New values: Booleans New type: bool, and new
values: True and False.

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”

In [2]: 3 < 2 In [6]: 5 == 5


Out[2]: False Out[6]: True

In [3]: 3 > 2 In [7]: 5 == 6


Out[3]: True Out[7]: False
“not
equals”
In [4]: 5 <= 1 In [8]: 5 != 6
Out[4]: False Out[8]: True

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!
Booleans 4
Concepts in this slide:
Relational expressions
Relational Operators [cont.] with string values.

The relational operators can also be used to compare strings


(in dictionary order, meaning, something is smaller if it is earlier in the dictionary):

In [1]: 'bat' < 'cat'


Important
Out[1]: True
If you want to compare two strings,
always use the relational operators,
In [2]: 'bat' < 'ant'
no need to try to compare every
Out[2]: False
element of the string. Python does
that automatically for you.
In [3]: 'bat' == 'bat'
Out[3]:
True
In Python (and most other
In [4]: 'bat' < 'bath' programming languages) uppercase
Out[4]: letters come before lowercase
True
letters in string ordering. See
In [5]: 'Cat' < 'bat' Digging Deeper section about
Out[5]: True the reason.
Booleans 5
Logical Operators Concepts in this slide:
New operators: logical.

in plain English They are and, or, not.

a: the cake has pineapple False


b: the cake is chocolate True
c: the cake has walnuts True
d: the cake is square False

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?

Or (slightly different from English…)


a or b: the cake has pineapple or the cake is chocolate True/False?
b or c: the cake has chocolate or the cake has walnuts True/False?
a or d: the cake has pineapple or the cake is square True/False?
Booleans 6
Concepts in this slide:
Logical Operators in Venn diagrams, visual
representation of logical
Venn Diagrams operations.

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.

not exp evaluates In [1]: not (3 > 5)


to the opposite of
Out[1]: True
the truth value of
exp
In [2]: not (3 == 3)
Out[2]: False
exp1 and exp2
evaluates to True
In [3]: (3 < 5) and ('bat' < 'ant')
iff both exp1 and
Out[3]: False
exp2 evaluate to
In [4]: (3 < 5) and ('bat' < 'cat')
True.
Out[4]: True
exp1 or exp2
In [5]: (3 > 5) or ('bat' < 'cat')
evaluates to True
Out[5]: True
iff at least one of
In [6]: (3 > 5) or ('bat' < 'ant')
exp1 or exp2
Out[6]: False
evaluates to True.
Booleans 8
Concepts in this slide:

Truth Tables: and and / or expressions


produce different Boolean
values.

exp1 exp2 exp1 and exp2


True True True
True False False
False True False
False False False
Truth Tables: or
exp1 exp2 exp1 or exp2
True True True
True False True
False True True
False False False
Booleans 9
Concepts in this slide:
Definition and examples
Predicates of predicates.

A predicate is simply any function that returns a Boolean value.


def isDarth (name):
"""determines if name is Darth Vader"""
return name == 'Darth Vader'

def isDivisibleBy(num, factor):


"""determines whether num is divisible by factor"""
return (num % factor) == 0

def isEven(n):
"""determines whether n is even"""
return isDivisibleBy(n, 2)

def sameLength(s1, s2):


"""determines whether strings s1 and s2 have the
same length"""
return len(s1) == len(s2)
Booleans 10
Concepts in this slide:
More Predicates Examples of predicates
with complex logical
expressions.
def isBetween(n, lo, hi):
"""determines if n is between lo and hi"""
return (lo <= n) and (n <= hi)

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 [1]: name = 'Esmeralda'


In [2]: name[0] To notice:
Out[2]: 'E' • The index of the first character
is 0 not 1, as you would expect.
That is a quirk of many
In [3]: name[1] programming languages.
Out[3]: 's' • The method lower returns a
new string that is the lowercased
In [4]: name.lower() version of the original one,
Out[4]: 'esmeralda' which doesn’t change. This
behavior is different from
In [5]: name cs1graphics objects.
Out[5]: 'Esmeralda'
Booleans 12
Your Turn: Write these predicates
Exercise 1: Write the predicate isVowel that behaves as shown
below:
In [6]: isVowel('E')
Out[6]: True

In [7]: isVowel('b')
Out[7]: False

Exercise 2: Use the predicate isVowel that you wrote above to


write a new predicate startsWithVowel that behaves like shown:
In [8]: startsWithVowel('Esmeralda')
Out[8]: True

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

In [1]: 'i' in 'generation' In [4]: 'get' in 'generation'


Out[1]: True Out[4]: False

In [2]: 'u' in 'generation' In [5]: 'nerati' in 'generation'


Out[2]: False Out[5]: True

In [3]: 'era' in 'generation' What other English words are in


Out[3]: True the string 'generation'?
s1 not in s2 is the same as not s1 in s2
In [6]: 'era' not in 'generation'
Out[6]: False

In [7]: 'get' not in 'generation'


Out[7]: True
Booleans 14
Short-circuit evaluation
of and and or
In exp1 and exp2 or exp1 or exp2, the expression
exp2 is not evaluated if the answer is determined by exp1.
In[14]: ((1/0) > 0) and (2 > 3)
---------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-17-5e0d829f2dca> in <module>()
----> 1 ((1/0) > 0) and (2 > 3)

ZeroDivisionError: integer division or modulo by zero

In[15]: (2 > 3) and ((1/0) > 0)


Out[15]: False

In[16]: (2 < 3) or ((1/0) > 0)


Out[16]: True

Booleans 15
Combining logical operators
What cake do I like?

(cake is chocolate) or (cake has pineapple) and (cake is square)

and takes precedence over or (like * over +)

((cake is chocolate) or (cake has pineapple)) and (cake is square)

Parentheses take precedence

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'

# determines if n is a prime integer less than 100


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
or not (isDivisibleBy(n,2)
No continuation or isDivisibleBy(n,3)
characters are needed in
or isDivisibleBy(n,5)
parenthesized
expressions or isDivisibleBy(n,7)))
Booleans 17
Parentheses Instead of Continuation Characters

If you don’t like continuation characters for multiline expressions,


you can avoid them by wrapping the expression in explicit parentheses,
like the big blue parentheses below:
def isHogwartsHouse(s):
return (s == 'Gryffindor' or s == 'Hufflepuff'
or s == 'Ravenclaw' or s == 'Slytherin' )
# determines if n is a prime integer less than 100
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
or not (isDivisibleBy(n,2)
or isDivisibleBy(n,3)
or isDivisibleBy(n,5)
or isDivisibleBy(n,7))))
Booleans 18
ASCII Table: uppercase vs. lowercase

In computer programs, all data is stored as numbers (binary numbers made of


0 and 1s. Take CS 240 to learn more). ASCII is a standard that specifies the
mapping between keyboard characters and numbers. When you compare “A”
and “a”, you are comparing the underlying numbers 65 and 97.
Booleans 19
Test your knowledge
1. What is the result of relational expressions? What is the result of logical
expressions? What makes them different?
2. How does the comparison of string values work? Can you provide an
example to illustrate?
3. Operators like > , or are called binary operators, while not is called a
unary operator. Can you give an educated guess for the why?
4. [MATH] Relational operators are used in Math to describe intervals of
numbers. Draw a picture showing the interval 10 to 20 (excluding 20). How
would you write this in Python? What about the intervals of numbers less
than 5 but greater than 15. Drawing the picture helps visualize relations.
5. Write the Truth Table for the expression not (exp1 and exp2)
6. Is there any difference between a predicate and a function?
7. What is the result of the expression '$' > '%' . How would you
explain that to someone?
8. In the expression 3 < 5 and 'bat' < 'cat' (notice there are no
parens), does and have priority over <? Explain.

Booleans 20

You might also like