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