Python Logical Operators and Truthiness
What you will learn
- The three logical operators:
and,or,not - Their truth tables and the order they run in
- That
andandorreturn one of their operands, not always a boolean - What counts as false (truthiness)
- The classic mistake
x == 1 or 2, and how to fix it - De Morgan's laws, and
any()andall()
1. Combining conditions
One comparison is often not enough. "Can this person enter?" may need both an age check and a ticket check. Logical operators join conditions:
| Operator | Meaning | True when |
|---|---|---|
a and b |
both | both a and b are true |
a or b |
either | at least one is true |
not a |
opposite | a is false |
age = 20
has_id = True
print(age >= 18 and has_id)
print(age >= 18 or has_id)
print(age < 18 and has_id)
True
True
False
In an if, this removes nesting (lesson 5.2): if age >= 18 and has_id: replaces two if lines.
Quick check: if `a` is `False`, what is `a or True`?
True. An or is true when at least one side is true.
2. Truth tables
Here is every case for two booleans:
a |
b |
a and b |
a or b |
|---|---|---|---|
True |
True |
True |
True |
True |
False |
False |
True |
False |
True |
False |
True |
False |
False |
False |
False |
And not simply flips: not True is False, and not False is True.
3. The order of the operators
From highest to lowest: comparisons, then not, then and, then or. So and binds tighter than or, like multiplication and addition:
print(True or False and False)
print((True or False) and False)
print(not True or True)
print(not (True or True))
True
False
True
False
True or False and FalseisTrue or (False and False), soTrue.- Brackets change it:
(True or False) and FalseisFalse.
Brackets cost nothing, so use them when a line mixes and with or.
4. and and or return an operand
and and or do not always give True or False. They give back one of the two values:
a and b: ifais false, the answer isa; otherwise it isb.a or b: ifais true, the answer isa; otherwise it isb.
print(1 and 2, 0 and 2, "a" and "b", "" and "x")
print(1 or 2, 0 or 2, "" or "default", None or "x")
2 0 b
1 2 default x
(The last value of the first line is the empty string, which shows as nothing.) This is useful for default values:
name = ""
print(name or "Anonymous")
print("Rina" or "Anonymous")
Anonymous
Rina
If name is empty (false), or gives the default.
5. What counts as false
Any value can be used in a condition. These are false (falsy):
| Value | Type |
|---|---|
False |
bool |
None |
NoneType |
0, 0.0, 0j |
numbers |
"" |
empty text |
[], (), {}, set(), range(0) |
empty collections |
falsy = [None, False, 0, 0.0, 0j, "", [], (), {}, set(), range(0)]
print([bool(v) for v in falsy])
[False, False, False, False, False, False, False, False, False, False, False]
Everything else is true (truthy), including things that look empty or negative:
print(bool(-1), bool("0"), bool("False"), bool([0]), bool([[]]), bool(" "))
True True True True True True
bool("0") and bool("False") are true because they are non-empty text; the list [0] is true because it contains something. The zero values of Decimal and Fraction are false too: bool(Decimal(0)) is False.
6. The classic mistake: x == 1 or 2
In English we say "if x is 1 or 2". In Python this is wrong:
n = 7
print(n == 1 or 2)
print(bool(n == 1 or 2))
2
True
Python reads it as (n == 1) or 2. The first part is False, so the answer is 2, which is true, always. The test never fails. Write it properly:
n = 7
print(n == 1 or n == 2 or n == 3)
print(n in (1, 2, 3))
False
False
The in form is shorter and clearer. The same mistake happens with text:
color = "blue"
print(color == "red" or "blue")
print(color == ("red" or "blue"))
print(color in ("red", "blue"))
blue
False
True
The first line is true for any color, because "blue" is non-empty. The second line works out ("red" or "blue") first, which is "red". Only the third is correct.
7. De Morgan's laws
Two rules help you simplify a not in front of a bracket:
| Rule | In Python |
|---|---|
not (a and b) equals (not a) or (not b) |
"not both" means "at least one is missing" |
not (a or b) equals (not a) and (not b) |
"not either" means "neither" |
Test them yourself on all four cases:
for a in (True, False):
for b in (True, False):
assert (not (a and b)) == ((not a) or (not b))
assert (not (a or b)) == ((not a) and (not b))
print("both laws hold")
both laws hold
Use them to rewrite a confusing condition. "Not (young and poor)" becomes "not young, or not poor".
Careful with not and comparisons: not 1 == 2 means not (1 == 2), which is True, because not binds looser than ==.
8. any() and all()
For a whole collection of conditions:
| Function | True when |
|---|---|
any(items) |
at least one item is true (False for an empty collection) |
all(items) |
every item is true (True for an empty collection) |
print(any([False, 0, "a"]), any([]))
print(all([True, 1, "a"]), all([]), all([True, 0]))
print(any(x > 5 for x in [1, 2, 9]), all(x > 0 for x in [1, 2, 3]))
True False
True True False
True True
all([]) is True because no item breaks the rule. The last line uses a generator expression (chapter 12).
Worked example: can she get the discount?
A discount is given to members, or to anyone over 60, but only if the order is at least 500 (made-up rules).
member = False
age = 65
order = 700
discount = (member or age > 60) and order >= 500
print(discount)
True
| Part | Value |
|---|---|
member |
False |
age > 60 |
True |
(member or age > 60) |
True |
order >= 500 |
True |
| whole condition | True and True, so True |
Without the brackets, member or age > 60 and order >= 500 would be read as member or (age > 60 and order >= 500). That gives the same answer here, but a different one for a member with a small order.
Common mistakes
- Writing
x == 1 or 2. Writex == 1 or x == 2, orx in (1, 2). - Forgetting that
andgoes beforeor. Use brackets. - Thinking
a and balways returns a boolean. It returns one of the operands. - Treating
"0","False"or[0]as false. They are true. - Writing
not x == yand reading it as(not x) == y.
Key takeaways
and,orandnotcombine conditions; the order is comparisons,not,and,or.a and banda or breturn one of the operands, which makesvalue or defaulta handy idiom.- False values:
False,None, zero, and empty text or collections. Everything else is true. - Never write
x == 1 or 2: usex == 1 or x == 2orx in (1, 2). any()andall()test a whole collection; use brackets when mixingandwithor.
Practice
1. What do True and False, True or False and not False give?
Show answer
False, True and True.
2. What does 0 or "none" give? And "hi" and 5?
Show answer
"none" (because 0 is false, so or gives the second value) and 5 (because "hi" is true, so and gives the second value).
3. What is wrong with if answer == "y" or "yes":, and what is the fix?
Show answer
"yes" is a non-empty string, so the condition is always true. Write if answer == "y" or answer == "yes": or if answer in ("y", "yes"):.
4. Write a condition that is true when score is between 50 and 100 inclusive, in two ways.
Show answer
score >= 50 and score <= 100, or the chained form 50 <= score <= 100 (lesson 5.6).
5. Which of these are false: [], [0], "", " ", 0.0, "0", None?
Show answer
[], "", 0.0 and None. The others ([0], " " and "0") are true.
6. Use all to check that every mark in [60, 75, 90] is at least 50.
Show answer
all(m >= 50 for m in [60, 75, 90]) gives True.