Macbook, mouse, Apple Watch and mouse

Code Snippets: Python – If statements with multiple conditions

Sometimes when writing a Python script we have to deal with if statements where multiple conditions need to verified at the same time.

Setup – Integer flags

First let’s declare 3 flag variables, that we will call foo, bar and baz (I know, quite original). Only the third one is equal to 1 the other two will be initialised with a 0.

# Different ways to test multiple
# flags at once in Python
foo = 0
bar = 0
baz = 1

Now let’s have a look at some options to evaluate the different flags

Option 1

This is a classic way of evaluating multiple variables at the same time. We are just going to use the or operator to verify that at least one of those are equal to 1. This is how you can do so in Python:

if foo == 1 or bar == 1 or baz == 1:
    print('statement true')
else:
    print('statement false')

Option 2

A more concise way of expressing the same statement is to omit the equalities. In python a statement formulated as if variable evaluates the truthiness of the variable itself, and a variable equal to 1 is evaluated as True, 0 as False.

if foo or bar or baz:
    print('statement true')
else:
    print('statement false')

Option 3

Another way of achieving the same result in a more pythonic way is to evaluate if the element 1 is present in the tuple made of the variables foo, bar and baz:


if 1 in (foo, bar, baz):
    print('statement true')
else:
    print('statement false')

Option 4

A final approach is to use the function any. This function returns True if at least one value inside a list or a tuple is equal to True (or equally to 1). We can then evaluate it on the tuple that contains foo, bar and baz.

if any((foo, bar, baz)):
    print('statement true')
else:
    print('statement false')

Posted

in

by