objects of different types, except different numeric types, are never equal
equals (==) will always return False for different types →
not equals (!=) will always return True for different types →
the <, <=, > and >= operators…
will raise a TypeError if the objects are of different types that cannot be compared →
will happily compare numeric types (for example comparing floats and ints works as you'd expect)! →
Logical Operators
What are Logical Operators?
Logical Operators are operators that combine Boolean values.
these operators always return another Boolean value.
furthermore, these operators can be used to create more complex Boolean expressions.
Three Logical Operators:
and -
takes two operands, one on each side
to return True, both sides of the operator must be True →
or -
takes two operands, one on each side
to return True,at least one side of the operator must be True →
not -
only takes one operand to the right
to return True, the original value on the right must evaluate to False →
two nots cancel eachother out (fun!) →
Logical Operators in Action
Note that these are all expressions that result in a value that's of type bool:
>>> True and False
False
>>> True and True
True
>>> True or False
True
>>> not True
False
>>> not not True
True
That Can Get Complicated!
Yes. We'll use truth tables to show what each operator will return.
a truth table is a concise table of Boolean values that describes the semantics of an operator
it will go through each possible combination of operands and specify the resulting Boolean value
each row will represent a combination of operands
each column will represent a value of one operand
…with the exception of the last column, which represents the resulting value
Truth Table - AND
and takes two operands. Each operand can be True or False (or will evaluate to True or False!).
Can you guess how many possible combinations there are for these two operands?What will the Truth Table look like? →
"""
(using p and q to represent the operands
...and t and f for true and false)
p | q | p and q
----------------
f | f | f
f | t | f
t | f | f
t | t | t
"""
Truth Table - OR
Let's fill out a truth table for or! →
"""
(using p and q to represent the operands
...and t and f for true and false)
p | q | p and q
----------------
f | f | f
f | t | t
t | f | t
t | t | t
"""
Truth Table - NOT
Let's fill out a truth table for not! →
"""
(using p and q to represent the operands
...and t and f for true and false)
p | not p
-----------
t | f
f | t
"""
Let's Evaluate Some Simple Boolean Expressions
True and False →
True and not False →
True or False →
True or not False →
False or False →
not False and not False →
Chaining Operators
Boolean, comparison and other operators can be combined to create complex Boolean expressions! For example: