Python Logical Operators
Logical operators combine boolean expressions so you can test several conditions at once.
Combining conditions
Logical operators let you build more expressive conditions by joining or inverting boolean values. Python uses plain English keywords for them: and, or, and not. They are most often used together with comparison operators to describe rules like "the user is an adult and has a valid ticket".
Using and, or, and not
age = 25
has_ticket = True
can_enter = age >= 18 and has_ticket
print(can_enter) # True
weekend = False
holiday = True
day_off = weekend or holiday
print(day_off) # True
print(not can_enter) # FalsePython evaluates these operators lazily, a behavior called short-circuit evaluation. With and, if the first operand is False the overall result must be False, so Python never looks at the second operand. With or, if the first operand is True the result must be True, so the rest is skipped. This is not just a speed optimization; it lets you guard against errors.
Short-circuit evaluation as a safety guard
items = []
# Because items is empty, len(items) > 0 is False,
# so Python never evaluates items[0] and avoids an error.
if len(items) > 0 and items[0] == "first":
print("found it")
else:
print("list was empty or did not match") # this runsA subtle but powerful detail is that and and or do not always return a literal True or False. They return one of the actual operands. This lets you use or to supply a default value and and to pick between values, a pattern you will see often in real Python code.
and and or return operands, not just booleans
name = ""
display = name or "Guest" # empty string is falsy
print(display) # Guest
value = 5
result = value and value * 2 # value is truthy, so return value * 2
print(result) # 10- Use and when every condition must hold true.
- Use or when any one condition passing is enough.
- Use not to flip a condition, but avoid stacking it too deep since double negatives are hard to read.
- Values like 0, empty strings, empty lists, and None are treated as falsy; most other values are truthy.
- When mixing and and or, use parentheses to make the grouping obvious.