在“if"语句中设置多行条件样式? [英] Styling multi-line conditions in 'if' statements?
问题描述
有时我将 if
s 中的长条件分成几行.最明显的方法是:
Sometimes I break long conditions in if
s 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
在视觉上不是很吸引人,因为动作与条件融合在一起.然而,这是使用正确的 4 个空格缩进的自然方式.
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.
目前我正在使用:
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?
推荐答案
您不需要在第二个条件行上使用 4 个空格.也许使用:
You don't need to use 4 spaces on your second conditional line. 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.
甚至:
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
这是风格指南,其中(自 2010 年起)建议使用方括号.
Here's the Style Guide, which (since 2010) recommends using brackets.
这篇关于在“if"语句中设置多行条件样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!