when to use if vs elif in python

Sean Geoffrey Pietz picture Sean Geoffrey Pietz · Apr 1, 2014 · Viewed 29.8k times · Source

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'

Is it better to write:

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?

Edit:

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 will still equal [1,2,3]

Answer

Gareth Latty picture Gareth Latty · Apr 1, 2014

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.

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 doesn't make much sense given the example, but potentially could in a more realistic case). This ambiguity is removed if elifs 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 ifs 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 ifs 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).