conditional – when to use if vs elif in python
conditional – when to use if vs elif in python
Ill 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.
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
Suddenly, there is a potential bug if the user intended that case to be mutually exclusive (obviously, this doesnt 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 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, its best to stick to one way).
Check this out to understand the difference:
>>> a = 2
>>> if a > 1: a = a+1
...
>>> if a > 2: a = a+1
...
>>> a
4
versus
>>> a = 2
>>> if a > 1: a = a+1
... elif a > 2: a = a+1
...
>>> a
3
The first case is equivalent to two distinct if
s with empty else
statements (or imagine else: pass
); in the second case elif
is part of the first if
statement.
conditional – when to use if vs elif in python
In some cases, elif
is required for correct semantics. This is the case when the conditions are not mutually exclusive:
if x == 0: result = 0
elif y == 0: result = None
else: result = x / y
In some cases it is efficient because the interpreter doesnt need to check all conditions, which is the case in your example. If x is negative then why do you check the positive case? An elif
in this case also makes code more readable as it clearly shows only a single branch will be executed.