and, or
`and` is true only when both sides are; `or` is true when at least one is, and both stop as soon as they know the answer.
Used in 102 lessons of the course, from 00.01.
and and or combine conditions into one.
a and bis true only when bothaandbare.a or bis true when at least one is.
Python evaluates left to right and stops as soon as the answer is clear. That's why False and f() never calls f(). This is called short-circuit evaluation, and it lets you write safe checks.
Note: they return one of the two values, not always True or False. "" or "hello" gives "hello".
When you mix both, and is evaluated before or. Use parentheses to keep it readable.
In the course, the line word in t or word in d.lower() in the glossary filter uses or: a term matches if the word appears in its name or in its description.
age = 20
print(age >= 18 and age < 65)
Reach for it when: a decision depends on several conditions: all must hold (`and`) or any one is enough (`or`).
Examples
Common mistake
color = "green"
if color == "red" or "blue":
print("warm or cool")
else:
print("other")Why: `"blue"` is a non-empty string, so it counts as true. The condition reads as `(color == "red") or "blue"` and always passes.
How to write it: Compare each side: color == "red" or color == "blue", or use color in ("red", "blue").
Common mistake
a = True b = False c = True print(a or b and c) print((a or b) and c) print(b or c and b)
Why: `and` is evaluated before `or`, so `a or b and c` is `a or (b and c)`. Without parentheses it's easy to read it differently.
How to write it: Add parentheses to show your intent.
