Code Snippets: Python - If statements with multiple conditions

Learn Python if statements with multiple conditions using and, or, elif, parentheses, membership checks, and readable examples.
python
Author

Federico Viscioletti

Published

February 17, 2023

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 and and or between complete expressions: age >= 18 and has_ticket.
  • Do not write if age == 18 or 21; Python treats 21 as a separate truthy value. Write if age in (18, 21) instead.
  • Add parentheses when mixing and and or so the rule is unambiguous.
  • Prefer if items: to if len(items) > 0 when checking whether a list, tuple, or set is non-empty.
  • Use is None for None, rather than == None.

For more examples of conditional logic in data work, see the guide to conditional columns in pandas.

Share this article