Writing Multi-line if Statements in Python

May 25, 2021
Cover image for Writing Multi-line if Statements in Python

When programming, it's a good practice to make sure your lines of code don't stretch out too long. You may have to scroll horizontally to see code that didn't fit your screen. Or, code may be harder to read due to word wrapping. There are many ways of formatting multi-line if statements in Python. However, I prefer to use parenthesis and have each condition be on a separate line. This allows the ability to add and remove conditions easily without the hassle of further formatting.

if (condition1 == 'value1' and
condition2 == 'value2' and
condition3 == 'value3' and
condition4 == 'value4' and
condition5 == 'value5'):
do_something()
if (condition1 == 'value1' or
condition2 == 'value2' or
condition3 == 'value3' or
condition4 == 'value4' or
condition5 == 'value5'):
do_something()

Also, if you notice that every condition uses either AND's or OR's, you could use the any or all keyword.

The all function checks if every item in a list evaluates to true. This is similar to using multiple AND's.

if all([
condition1 == 'value1',
condition2 == 'value2',
condition3 == 'value3',
condition4 == 'value4'
]):
do_something()

The any function checks if at least one item in a list evaluates to true. This is similar to using multiple OR's.

if any([
condition1 == 'value1',
condition2 == 'value2',
condition3 == 'value3',
condition4 == 'value4'
]):
do_something()

There are different ways of formatting your code for multi-line if statements in Python, so it's a good idea to verify that your approach meets the style guide or observe your team's coding style. It's important to maintain consistency throughout your project.