Difference between elif and if statements?

Looking again at the solution code, I tried to replace the two elif statements with if statements and the results were exactly the same.
Since we were taught that return is a statement which assigns a value to the function call, then when it follows a conditional (if) statement, this value is “stored” . Thus, another if statement may follow, which is “independent” from the previous. In that case, elif seems to be unnecessary.
Also, recalling again the lesson about Else If statements (example with donations), print was used in the code, not return, so the use of elif was the only way in order to be able to “control the order of checking each conditional statement” and have accurate results.

In conclusion, I am wondering, in any function with conditional statements when return is used , can if replace elif withοut changing the results ?

1 Like

That is because they all have return in their branch. Were it not the case, we would definitely need elif to omit previous states that passed their condition. The code resumes after the final else (or elif), a point that all cases will reach if there is no return. Being inside a function gives us this extra out to exit the function so elif is superfluous.


This is my code. In case of call - print(max_num(5, 3, 3)) - it prints only 5, although it seems to be “It’s a tie!” also, because of if (not elif) operators. Am I wrong?

def max_num(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
if num2 > num1 and num2 > num3:
return num2
if num3 > num1 and num3 > num2:
return num3
if num1 == num2 or num1 == num3 or num2 == num3:
return “It’s a tie!”
print(max_num(5, 3, 3))

Return means handing back data to the function call, thus when the code reaches the line return num1 the function ends, so it never does the tie comparison