Combining Boolean expressions with and
, or
, and not
Logical operators evaluate Boolean expressions and return True
or False
.
Operator | Description | Example |
---|---|---|
and | True if both operands are True | True and False → False |
or | True if at least one operand is True | True or False → True |
not | Inverts the Boolean value | not True → False |
x = 5
y = 10
# and
print(x > 0 and y > 0) # True (both conditions True)
# or
print(x < 0 or y > 0) # True (second condition True)
# not
print(not (x == y)) # True (x == y is False, not False → True)
Python stops evaluating as soon as the result is determined:
def side_effect():
print("Function called")
return True
print(False and side_effect()) # side_effect() not called
print(True or side_effect()) # side_effect() not called
Any object can be tested for truthiness:
name = ""
print(not name) # True (empty string is falsy)
items = [1, 2, 3]
if items and len(items) > 2:
print("List has items")
any()
and all()
for multiple checks on iterables.scores = [85, 90, 78]
print(all(score >= 70 for score in scores)) # True (all pass)
print(any(score < 60 for score in scores)) # False (none below 60)