Ask Python a question about two values and get back True or False.
| Operator | Asks | Example |
|---|---|---|
| == | equal to? | 5 == 5 → True |
| != | not equal to? | 5 != 3 → True |
| > < | greater / less than? | 3 > 5 → False |
| >= <= | greater / less or equal? | 5 >= 5 → True |
A single = assigns; a double == compares.
# equal to
5 == 5
# ans: True
5 == 3
# ans: False
"hello" == "hello"
# ans: True
# not equal to
5 != 3
# ans: True
5 != 5
# ans: False
"a" != "b"
# ans: True
# greater than
5 > 3
# ans: True
3 > 5
# ans: False
# less than
5 < 3
# ans: False
3 < 5
# ans: True
On a number line, "greater" means "further to the right".
# greater or equal
5 >= 5
# ans: True
5 >= 3
# ans: True
# less or equal
5 <= 3
# ans: False
5 <= 5
# ans: True
# chain comparisons
3 < 5 < 7
# ans: True (both conditions)
1 < 2 < 3 < 4
# ans: True
5 < 3 < 7
# ans: False (first fails)
A chain is a shorthand for comparisons joined by and; it stops at the first False.
True or False? Decide, then press →.
# comparison chain?
3 < 5 < 7
# ans: True
# what happens?
5 < 3 < 7
# ans: False (5 < 3 is False)
# comparison with different types?
5 == 5.0
# ans: True
# is vs ==?
a = [1, 2]
b = [1, 2]
a == b
# ans: True
a is b
# ans: False
== compares contents; is asks whether both names point at the very same object.
# what is result?
"10" == 10
# ans: False (different types)
# string comparison?
"apple" < "banana"
# ans: True (lexicographic)
Strings compare letter by letter, like a dictionary: "a" comes before "b".
# what about this?
True == 1
# ans: True
False == 0
# ans: True
# chained equality?
5 == 5 == 5
# ans: True
5 == 5 == 6
# ans: False
# None comparison?
None == None
# ans: True
x = None
x is None
# ans: True
There is only one None, so x is None is the usual way to test for it.
# empty comparisons?
[] == []
# ans: True
[] is []
# ans: False
"" == ""
# ans: True
Every comparison gives True or False.
anda < b < c is a < b and b < c.
== vs isSame contents vs the same object in memory.
"10" == 10 is False, but 5 == 5.0 and True == 1 are True.