How do I write conditional statements across lines in an if statement?

Asked 1 years ago, Updated 1 years ago, 114 views

What kind of method should I use to write conditions across lines for if?

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

This way, code3 is on the same line as do_something so the code looks dirty

In Python, we usually indent with a space of 4 spaces, so I wrote it like this.

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

This is kind of weird, too. Is there a rule set in PEP?

python coding-style if문

2022-09-21 20:48

1 Answers

The relevant style guide is located at PEP0008.

Usually, we write from the second line.

from the second line
if (cond1 == 'val1' and cond2 == 'val2' and 
       cond3 == 'val3' and cond4 == 'val4'):
    do_something

Because it's enclosed in parentheses

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

#or

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

You can write it as.

Although not recommended in the style guide, it is also possible to write a slash (\) after removing parentheses

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

#or

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


2022-09-21 20:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.