本文介绍了编码样式和else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def foo(东西):


如果东西:

返回东西+ 1

其他:

返回-1


def foo(东西):


如果东西:

返回东西+ 1

返回-1


显然两者都做同样的事情。第一个是

可能更清晰,而第二个更简洁。


评论?


-

通过 http://www.teranews.com

def foo(thing):

if thing:
return thing + 1
else:
return -1

def foo(thing):

if thing:
return thing + 1
return -1

Obviously both do the same thing. The first is
possibly clearer, while the second is more concise.

Comments?

--
Posted via a free Usenet account from http://www.teranews.com

推荐答案



如果没有其他人会检查为什么把它放在那里?

if there is nothing the else will check why put it there?




怎么样:


def foo(东西):

if thing:

result =东西+ 1

否则:

结果= -1

返回结果


和:


foo = lambda thing:thing and thing + 1或-1

What about:

def foo(thing):
if thing:
result = thing + 1
else:
result = -1
return result

and:

foo = lambda thing: thing and thing + 1 or -1




和...或技巧是错误的(如果东西== -1?)和糟糕的风格。如果

你想要一个条件表达式,2.5提供一个:


的东西+ 1如果还有其他东西-1


没有微妙的逻辑错误,而且更明显更好。


关于原始帖子的主题,我个人更喜欢后者

(没有其他条款),因为太深的压痕水平不是很好

Thing。但是,如果一个多余的其他:会使代码更清晰

不知何故,一定要使用一个,因为这更像是个人品味而不是任何东西。

The and ... or trick is buggy (what if thing == -1?) and bad style. If
you -do- want a conditional expression, 2.5 provides one:

thing + 1 if thing else -1

No subtle logical bugs, and a good deal more obvious.

On the topic of the original posting, I personally prefer the latter
(no else clause), because too deep a level of indentation is not a Good
Thing. However, if a redundant else: would make the code clearer
somehow, by all means use one, because this is more a matter of
personal taste than anything.


这篇关于编码样式和else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!