Reputation: 12179
Noob question I know, but I need it confirmed since this occurs so often to me. Is there any point in using elif:
if you know that code won't be reached when previous block is true? Eg.
if foo:
return x
elif bar:
return y
Should just be:
if foo:
return x
if bar:
return y
Upvotes: 1
Views: 2898
Reputation: 359776
I can see at least three reasons to prefer if/elif
:
if/elif
won't break, but if/if
mightand at least two reasons to prefer if/if
:
That said, here's some recommended reading:
Upvotes: 7
Reputation: 40985
Multiple IF
statements means your code will check all the IF
conditions, whereas in case of elif:
, if one IF
condition satisfies it would not check other conditions. (As has been pointed out to me, this is ONLY true if none of the IF
statements has to return
from the code block)
In your case, it is OK to use the multiple IF
statement.
Upvotes: 0
Reputation: 8078
If you know it won't be true, then don't waste the interpreter's time with checking it. If you use if
it will be evaluated every time; however, elif
will only be evaluated if the previous if
condition was False
. In this case you are using return
, so you should be safe from that, but by changing logical flow based on a return is bad. You should have as few (preferably only one) code paths as possible. Also, it gives a clean, readable structure and makes the code path explicit. Readability counts, and explicit is better than implicit.
Upvotes: 1
Reputation: 16499
From the standpoint of the Python interpreter, no, there's no difference--or at least, there's no difference in terms of execution, though there may be some subtle difference in the way the two constructs are implemented.
But keep in mind that you are writing not just to the interpreter; you're writing for other programmers to read your code later. Write whatever you think makes your intention most clear.
Upvotes: 1
Reputation: 44112
There isn't any difference to the python interpreter; in fact, the two code snippets will internally compile to the same instructions (the compiler is smart enough to know that the code after the return will never be reached, and will optimize the else
part away completely.).
It's a matter of style, and readability.
Upvotes: 3