when to use if vs elif in python

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).

Leave a Comment