如果我有一个包含多个条件语句的函数,其中每个分支都被执行,则从函数返回.我应该使用多个 if 语句还是 if/elif/else?例如,假设我有一个函数:
If I have a function with multiple conditional statements where every branch gets executed returns from the function. Should I use multiple if statements, or if/elif/else? For example, say I have a function:
def example(x):
if x > 0:
return 'positive'
if x < 0:
return 'negative'
return 'zero'
这样写更好吗:
def example(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
两者都有相同的结果,但一个比另一个更有效或被认为更惯用?
Both have the same outcome, but is one more efficient or considered more idiomatic than the other?
有几个人说过,在第一个示例中,总是对两个 if 语句进行评估,但在我看来并非如此
A couple of people have said that in the first example both if statements are always evaluated, which doesn't seem to be the case to me
例如,如果我运行代码:
for example if I run the code:
l = [1,2,3]
def test(a):
if a > 0:
return a
if a > 2:
l.append(4)
test(5)
l 仍将等于 [1,2,3]
l will still equal [1,2,3]
我会将我的评论扩展到答案.
I'll expand out my comment to an answer.
在所有情况都返回的情况下,这些确实是等价的.在它们之间进行选择变得重要的是更具可读性.
In the case that all cases return, these are indeed equivalent. What becomes important in choosing between them is then what is more readable.
您的后一个示例使用 elif
结构来明确声明案例是互斥的,而不是依赖于它们隐含地来自返回的事实.这使得这些信息更加明显,因此代码更容易阅读,并且更不容易出错.
Your latter example uses the elif
structure to explicitly state that the cases are mutually exclusive, rather than relying on the fact they are implicitly from the returns. This makes that information more obvious, and therefore the code easier to read, and less prone to errors.
比如说,有人认为还有另一种情况:
Say, for example, someone decides there is another case:
def example(x):
if x > 0:
return 'positive'
if x == -15:
print("special case!")
if x < 0:
return 'negative'
return 'zero'
突然之间,如果用户希望这种情况是互斥的,就会出现一个潜在的错误(显然,这在示例中没有多大意义,但在更现实的情况下可能会发生).如果使用了 elif
,则可以消除这种歧义,并且该行为对于添加代码的人在他们添加代码时可能正在查看的级别是可见的.
Suddenly, there is a potential bug if the user intended that case to be mutually exclusive (obviously, this doesn't make much sense given the example, but potentially could in a more realistic case). This ambiguity is removed if elif
s are used and the behaviour is made visible to the person adding code at the level they are likely to be looking at when they add it.
如果我遇到您的第一个代码示例,我可能会假设选择使用 if
s 而不是 elifs
意味着这些情况是不是 是互斥的,所以像改变 x
的值这样的事情可能会被用来改变 if
的执行(显然在这种情况下,意图是显而易见的并且是相互的排他性的,但同样,我们谈论的是不太明显的情况 - 并且一致性很好,所以即使在一个简单的例子中,当它很明显时,最好坚持一种方式).
If I were to come across your first code example, I would probably assume that the choice to use if
s rather than elifs
implied the cases were not mutually exclusive, and so things like changing the value of x
might be used to change which if
s execute (obviously in this case the intention is obvious and mutually exclusive, but again, we are talking about less obvious cases - and consistency is good, so even in a simple example when it is obvious, it's best to stick to one way).
这篇关于何时在 python 中使用 if vs elif的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!