Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (50.2k points)

Sometimes I break long conditions in ifs onto several lines. The most obvious way to do this is:

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


It isn't very appealing visually, because the action blends with the conditions. However, it is the natural way using the correct Python indentation of 4 spaces.

For the moment I'm using:

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


But this isn't very pretty. :-)

Can you recommend an alternative way?

1 Answer

0 votes
by (106k points)

For multi-line, if statement you can use the following way:-

if(cond1 == 'val1' and \ 

cond2 == 'val2' and \ 

cond3 == 'val3' and \ 

cond4 == 'val4'):


If you will follow below-mentioned way then it will shave a few characters and makes it clear that there's no subtlety to the condition.

if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ): 

if any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):

Related questions

Browse Categories