After this lesson you can express rules such as "the member is over 18 and has a library card" in code, and you will know exactly what Python does with them.
Three operators
Comparisons answer a single question. Real rules usually combine several. Python has three logical operators for this, spelled as plain English words:
andisTrueonly when both sides areTrue.orisTruewhen at least one side isTrue.notreverses a single value.
Here they are applied to a library member:
age = 25
has_card = True
print(age >= 18 and has_card)
print(age < 18 or has_card)
print(not has_card)True
True
FalseTruth tables
When you combine two values, there are only four possible pairs, so you can list every outcome. This is called a truth table. Rather than memorise it, let Python print it:
for a in (True, False):
for b in (True, False):
print(a, b, "and:", a and b, "or:", a or b)True True and: True or: True
True False and: False or: True
False True and: False or: True
False False and: False or: FalseThe loops here belong to a later section of the course. What matters is the output. and gives True on the first row only. or gives False on the last row only.
Order of evaluation
When several operators appear in one expression, not is worked out first, then and, then or. That means or has the lowest priority, which regularly catches people out.
print(True or False and False)
print((True or False) and False)True
FalseThe first line works out False and False first, which is False, and then True or False, giving True. The second line forces the or to happen first. A reliable habit: whenever you mix and with or, add brackets, even where Python would get it right without them.
Short-circuit evaluation
Python reads from left to right and stops as soon as the final answer is certain. With and, a False on the left settles the matter, so the right side is never looked at. With or, a True on the left does the same.
def loud(label):
print("checking", label)
return True
print(False and loud("first"))
print(True or loud("second"))
print(True and loud("third"))False
True
checking third
TrueOnly the third line triggered the function call. You have not seen functions yet, so just read loud as "a check that announces itself". Short-circuiting is useful for protecting a risky check behind a safe one. For example, count != 0 and total / count > 5 never divides by zero, because the division is only reached when count is not zero.
What and and or really return
An expression such as a or b does not always produce True or False. It returns whichever operand decided the answer. For or, that is the first value that is truthy, or the last value if none are. For and, it is the first falsy value, or the last value if none are.
print("" or "guest")
print("Maya" or "guest")
print(0 and "never shown")
print(5 and "shown")guest
Maya
0
shownThis gives a common pattern for filling in a default. name = typed_name or "guest" uses the typed name when it is not empty and the word guest otherwise. The next lesson explains exactly which values count as truthy and falsy.
Using brackets and splitting long conditions
Long conditions are easier to read when each part has a meaningful name.
age = 16
with_adult = True
old_enough = age >= 18
can_enter = old_enough or (age >= 13 and with_adult)
print(can_enter)TrueNaming the pieces as separate variables makes each rule easy to test and easy to change later.
Thinking in plain English first
When a rule feels tangled, say it aloud in ordinary words before writing any code. "A member can borrow if their card is valid and they owe nothing, or if a librarian approves it." The words and, or and not in your sentence usually map straight onto the Python operators, and the commas in your speech tell you where the brackets belong. Then test the rule with a handful of cases, including the edge ones: a valid card with a fine, an expired card with approval, and so on. A rule that works for all of your examples is far more trustworthy than one that merely looks right.
Common mistakes
- Writing
x == 1 or 2. Python reads it as(x == 1) or 2, and the 2 is always truthy. Writex == 1 or x == 2, or usex in (1, 2). - Writing
age >= 13 and < 18. Each side ofandmust be a complete expression. Chain it instead:13 <= age < 18. - Mixing
andandorwithout brackets. The result may differ from what you meant. - Using
&and|in place ofandandor. Those are bitwise operators, which do something different. - Writing
not x == yand misreading it. It meansnot (x == y). Usex != y, which is clearer.
A video version of this topic is in the video course at /learn/python/.
Exercise
A cinema lets someone in if they are at least 18, or if they are at least 12 and are with an adult. Set age = 14 and with_adult = False. Print whether the person may enter, then change with_adult to True and print again.
Show a possible answer
age = 14
with_adult = False
print(age >= 18 or (age >= 12 and with_adult))
with_adult = True
print(age >= 18 or (age >= 12 and with_adult))False
TrueKey points
- and is True only when both sides are True. or is True when at least one side is True. not flips True and False.
- not binds tightest, then and, then or. Use brackets to make the order obvious.
- Python stops evaluating as soon as the answer is known. This is called short-circuiting.
- and and or return one of their operands, not always True or False. This allows the x or default pattern.
- Write x == 1 or x == 2, not x == 1 or 2. The second form is always truthy.