Python if Statements with Multiple Conditions
When a Python decision depends on more than one condition, combine expressions with and, or, and not. Use parentheses when grouping makes the intended logic clearer.
The basic pattern is:
if condition_a and condition_b:
print("both conditions are true")
elif condition_a or condition_b:
print("at least one condition is true")
else:
print("neither condition is true")and versus or
Use and when every condition must be true. Use or when at least one condition is enough:
age = 25
has_ticket = True
is_member = False
if age >= 18 and has_ticket:
print("entry allowed")
if is_member or has_ticket:
print("discount available")Python evaluates and before or. When the rule is mixed, parentheses make the grouping explicit:
if (is_member or has_ticket) and age >= 18:
print("adult member or ticket holder can enter")Without the parentheses, age >= 18 and is_member or has_ticket is interpreted as (age >= 18 and is_member) or has_ticket, which may allow a ticket holder of any age.
Checking several values
For boolean or integer flags, Python can test truthiness directly. The values 0, None, and False are falsey; non-zero values and True are truthy.
foo = 0
bar = 0
baz = 1
if foo or bar or baz:
print("at least one flag is true")
else:
print("all flags are false")If the values are specifically flags equal to 1, an explicit comparison is also valid:
if foo == 1 or bar == 1 or baz == 1:
print("at least one flag is 1")For a collection of values, any() checks whether at least one item is truthy and all() checks whether every item is truthy:
flags = (foo, bar, baz)
if any(flags):
print("at least one flag is true")
if all(flags):
print("every flag is true")Membership checks with in
Use in when a value should match one of several allowed values. This is usually clearer than a long chain of or comparisons:
status = "pending"
if status in {"pending", "approved"}:
print("status can be processed")Common mistakes
- Use
andandorbetween complete expressions:age >= 18 and has_ticket. - Do not write
if age == 18 or 21; Python treats21as a separate truthy value. Writeif age in (18, 21)instead. - Add parentheses when mixing
andandorso the rule is unambiguous. - Prefer
if items:toif len(items) > 0when checking whether a list, tuple, or set is non-empty. - Use
is NoneforNone, rather than== None.
For more examples of conditional logic in data work, see the guide to conditional columns in pandas.