Skip to content Skip to sidebar Skip to footer

Expression Evaluation In If Elif Statements

Given code like this: if f(a) == 1: # do sth A elif f(a) == 2: # do sth B elif f(a) == 3: # do sth C else: # do sth D Does the expression f(a) get executed/evaluat

Solution 1:

Test it out:

In [7]: %paste
def f(a):
    print(a)

a = 4

if f(a) == 1:
    pass
elif f(a) == 2:
    pass
elif f(a) == 3:
    pass
else:
    pass

## -- End pasted text --
4
4
4

f(a) will keep on getting evaluated because there's no guarantee that f(a) will return the same result each time, so Python won't assume that it will. You can cache it with result = f(a) and use result in place of f(a).

If any of those if blocks happens to be True, the ones after it will not be tested.


Solution 2:

It's important to understand that an if statement with several elif statements can be expressed as a nested set of if and else blocks. That is, elif is just "syntactic sugar" for else: if (but it saves a level of indentation, so it's very handy!). The following block is equivalent to the first if and elif of your code:

if f(a) == 1:
    pass
else:
    if f(a) == 2:
        pass

With this in mind, the number of times the expression gets evaluated depends on what its result is, since you'll only go into the else parts if the previous tests were failed. If the first call to f(a) returns 1, then none of the other calls will be made. However, if all the tests fail (except perhaps the last one), they'll all need to be evaluated.

Similarly, within a logical expression using and and or, Python will short-circuit and not evaluate any parts of the expression that are not needed to determine the final value.

if f(a) == 1: # f(a) always gets evaluated here
     pass
elif f(a) == 2: # f(a) gets called a second time here if the "if" was failed
     pass
elif a<1 and f(a): # f(a) runs again only if both previous tests failed and a<1
     pass

So in summary, you can't tell how many times the function f(a) will run unless you know it's results ahead of time. If f(a) is not idempotent (that is, if it has side effects), you probably don't want to structure your code that way!


Solution 3:

I'm pretty sure it gets executed Every time it is called. ( I use python 2.7, wouldn't think it has changed in 3.x)

You could put a print statement in to verify.

That's why it could be better to only call it once and get the return value for your conditionals

You could cache the functions return value? But it could be more straight forward just to call function 1x:

f_value = f(a)
if f_value == 1:
    # do sth A
elif f_value == 2:
    # do sth B
elif f_value == 3:
    # do sth C
else:
    # do sth D

Post a Comment for "Expression Evaluation In If Elif Statements"