





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






Today ...
What is a Boolean value?
Python has special Boolean values
type(True) <class ’bool’>
type(False) <class ’bool’>
A detail of Python bool values
Any non-empty string or list denotes True
bool("spam") True
bool("False") True
bool([20, 10, 30]) True
bool([False]) True
bool("") False
bool([]) False
What does a Boolean expression return?
Comparison operators
5 == 5 True
5 == 6 False
True == False False
(5 == 5) == (4 == 4) True
(5 == 5) == (4 == 5) False
The == comparator is one of the (six) relational operators
x != y true if x is not equal to y x > y true if x is strictly greater than y x < y true if x is strictly less than y x >= y true if x ≥ y x <= y true if x ≤ y
Examples
5 != 6 True
6 != (5 + 1) False
2 > 3 False
2 <= 3 True
False < True True # False becomes 0, True becomes 1
[1, 2] <= [1, 2] True
[1, 2, 4] >= [1, 2, 3] True # since 4 >= 3 (subsequences)
And, or, and not form the basic logical operations used in formal logic
The expression x and y is true if x is true and y is true
x y x and y True True True True False False False True False False False False
(1 < 2) and (2 < 3) True
1 < 2 and 2 < 3 # parens not needed (but good) True
(1 > 2) and (2 < 3) bool([20, 10, 30]) True >>> bool([False]) True >>> bool("") False >>> bool([]) False ## Boolean expressions What does a Boolean expression return? - Boolean values (true or false) Comparison operators - The == operator tests if 2 operands are equal (equality) >>> 5 == 5 True >>> 5 == 6 False >>> True == False False >>> (5 == 5) == (4 == 4) True >>> (5 == 5) == (4 == 5) False The == comparator is one of the (six) relational operators x != y true if x is not equal to y x > y true if x is strictly greater than y x < y true if x is strictly less than y x >= y true if x ≥ y x <= y true if x ≤ y Examples >>> 5 != 6 True >>> 6 != (5 + 1) False >>> 2 > 3 False >>> 2 <= 3 True >>> False < True True # False becomes 0, True becomes 1 >>> [1, 2] <= [1, 2] True >>> [1, 2, 4] >= [1, 2, 3] True # since 4 >= 3 (subsequences) ## Logical operators And, or, and not form the basic logical operations used in formal logic - And is often called “conjunction” - Or is often called “disjunction” - Not is often called “negation” The expression x and y is true if x is true and y is true x y x and y True True True True False False False True False False False False - This is called a “truth table” >>> (1 < 2) and (2 < 3) True >>> 1 < 2 and 2 < 3 # parens not needed (but good) True >>> (1 > 2) and (2 < 3) False