Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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'): 

do_something

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'): 

do_something

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'):

Do_something

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...