In regards to the edit portion of your question when you said:
"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"
And then you provided this example:
l = [1,2,3]
def test(a):
if a > 0:
return a
if a > 2:
l.append(4)
test(5)
Yes indeed the list l
will still equal [1,2,3]
in this case, ONLY because you're RETURNING the result of running the block, because the return
statement leads to exiting the function, which would result in the same thing if you used elif
with the return statement.
Now try to use the print
statement instead of the return
one, you'll see that the 2nd if
statement will execute just fine, and that 4
will indeed be appended to the list l
using append
.
Well.. now what if the first if
statement changes the value of whatever is being evaluated in the 2nd if
statement?
And yes that's another situation. For instance, say you have a variable x
and you used if
statement to evaluate a block of code that actually changed the x
value.
Now, if you use another if
statement that evaluates the same variable x
will be wrong since you're considering x
value to be the same as its initial one, while in fact it was changed after the first if
was executed. Therefore your code will be wrong.
It happens pretty often, and sometimes you even want it explicitly to be changed. If that's how you want your code to behave, then yes you should use multiple if
's which does the job well. Otherwise stick to elif
.
In my example, the 1st if
block is executed and changed the value of x
, which lead to have the 2nd if
evaluates a different x
(since its value was changed).
That's where elif
comes in handy to prevent such thing from happening, which is the primary benefit of using it.
The other secondary good benefit of using elif
instead of multiple if
's is to avoid confusion and better code readability.