How to style multi-line conditions in 'if' statements in Python?


There are many ways you can style multiple if conditions. You don't need to use 4 spaces on your second conditional line. So you can use something like &minusl;

if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'):

# Actual code

You can also start the conditions from the next line −

if (
   cond1 == 'val1' and cond2 == 'val2' and
   cond3 == 'val3' and cond4 == 'val4'
):

# Actual code

Or you can provide enough space between if and ( to accomodate the conditions in the same vertical column.

if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'):

# Actual code

You can also do this without brackets, but note that PEP8 guidelines discourage this. For example,

if cond1 == 'val1' and cond2 == 'val2' and \
   cond3 == 'val3' and cond4 == 'val4':

# Actual code

Updated on: 05-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements