Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

python - 在“ if”语句中设置多行条件的样式?(Styling multi-line conditions in 'if' statements?)

Sometimes I break long conditions in if s onto several lines.

(有时我将if的长条条件分成几行。)

The most obvious way to do this is:

(最明显的方法是:)

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

Isn't very very appealing visually, because the action blends with the conditions.

(在视觉上不是很吸引人,因为动作与条件融为一体。)

However, it is the natural way using correct Python indentation of 4 spaces.

(但是,这是使用正确的4个空格的Python缩进的自然方法。)

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?

(您能推荐一种替代方法吗?)

  ask by Eli Bendersky translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need to use 4 spaces on your second conditional line.

(您不需要在第二条条件行上使用4个空格。)

Maybe use:

(可能使用:)

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

Also, don't forget the whitespace is more flexible than you might think:

(另外,不要忘记空白比您想象的更灵活:)

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

Both of those are fairly ugly though.

(两者都相当丑陋。)

Maybe lose the brackets (the Style Guide discourages this though)?

(也许丢了括号(尽管《 风格指南》不鼓励这样做)?)

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

This at least gives you some differentiation.

(这至少使您与众不同。)

Or even:

(甚至:)

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

I think I prefer:

(我想我更喜欢:)

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

Here's the Style Guide , which (since 2010) recommends using brackets.

(这是《 样式指南》 ,(自2010年起)建议使用括号。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...