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

PythonProgramming

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

raja
Published on 19-Apr-2018 16:22:42
Advertisements