Difference between "if" and "elif" and when to use what

I just finished the Advanced Python Code Challenges: Control Flow
Article and on the 5. Challenge called “Max Number” I stumbled upon something I wanted to ask the community.

This is the challenge description:

Create a function called max_num() that has three parameters named num1 , num2 , and num3 .

The function should return the largest of these three numbers. If any of two numbers tie as the largest, you should return "It's a tie!" .

I think there are two ways to solve this problem and I am not sure if both are equally valid. The first version I came up with uses only if-statements:

Version 1

def max_num(num1,num2,num3):
  if num1 > num2 and num1 > num3:
    return num1
  if num2 > num3 and num2 > num1:
    return num2
  if num3 > num2 and num3 > num1:
    return num3
  return "It's a tie!"

The second Version (which is basically identical to the official solution) uses if-, elif- and else statements.

Version 2

def max_num(num1,num2,num3):
  if num1 > num2 and num1 > num3:
    return num1
  elif num2 > num3 and num2 > num1:
    return num2
  elif num3 > num2 and num3 > num1:
    return num3
  else:
    return "It's a tie!"

Both versions do the exact same thing (at least I think they do).

So my question is, does it make a difference what version I use, if they give me the same result?
Version 2 feels a bit more sophisticated and elegant but that is just a gut feeling.
Is there a clear recommendation when to use “if” or “elif” statements?

Not sure if this is a dumb question, I’m pretty new to all of this. Thanks for your help.

As long as each branch is returning, we can use your first example. It changes everything if we do not return since the code is still progressing down the branches. In that case elif is the only way to prevent the other branches from being tested.

2 Likes

Thanks @mtf. That helped to clarify some things for me.

1 Like