Yeah, the thing to always remember about if-flow is that whenever it finds something is "True," it gives up entirely, (unless there is an "and" in there that makes it False).
So basically you want to line things up in such a way that it will check the most likely thing first, and only move to the next thing if that first thing is false.
As for this bit:
Also, what is the actual difference between a few separate if statements and a string of if/elif's?
I assume you mean:
Code: Select all
#something like this:
if potential > 0 and potential < 41:
$ damage = 25 + (p1_lvl*1)
#verses something like this?:
if potential > 0:
if potential < 41:
$ damage = 25 + (p1_lvl*1)
So far as I know, they would function identically, but the second way is a bit messier here. I only use the stcacked method if I will have two or more if statements in there or if the first if statement gets so bloated with ands and ors that I get confused trying to parse it.
One thing you DO need to keep in mind if you use "and" and "or" in those if statements is that you need to pay attention to how they get grouped. if you say:
if A > 0 and B > 10 or C > 5
but you mean that it should only trigger while A is 0 and B >10 or C >5, then you need to use parentheses, otherwise it will trigger every time C is over 5, and will only trigger otherwise if both A is > 0 and B is over 10. So basically:
if A > 0 and B > 10 or C > 5
would fail on A: 0 B: 12 C: 3 but succeed on A: 0 B: 6 C: 6
while
if A > 0 and (B > 10 or C > 5)
would only trigger if A is definitely over 0, and either B>10 or C>5, but doesn't need both of those. Make sense?
And again, line up ands and ors so that the most likely scenarios get knocked out first and it can move on to the next thing, rather than saving the real kicker for last.
Oh, and on rereading, you may have been asking what is the different between
if A:
if B:
if C:
and
if A:
elif B:
elif C:
Well the difference is that in the latter case, if it is A, it NEVER bothers with checking against B or the else statement, it just moves on to after that stack. It only gets to the "if B" part if the "if A" check fails. Which you use depends entirely on how you want it to work. If you do want to never check B if A is true, then you want to use elifs. In most cases this makes things faster since once it finds the true response, it never has to bother checking the other ones.
On the other hand, if the things that happen after "if A" triggers might change B, so that B would trigger after that block has finished, and you want that to happen, then you might just want to use if statements like in the first case. There are plenty of cases where you'd want to use either, but typically if it doesn't matter, elif is the more efficient.