简体   繁体   中英

python “if” versus “and” function execution order

Is there any functional difference between the following two blocks of code? I'm concerned mainly with the order in which the functions are called. Are functions executed sequentially in the first if statement?

First,

if func1() and func2() and func3() and func4():
    do stuff

Second,

if func1():
    if func2():
        if func3():
            if func4():
                do stuff

Yes, Python evaluates expressions from left to right. The functions will be called in the same order. From the reference documentation :

Python evaluates expressions from left to right.

Moreover, func2() will not be called if func1() returned a false value, both when using and and when nesting if expressions. Quoting the boolean operations documentation :

The expression x and y first evaluates x ; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Because in the expression func1() and func2() , func2() will not be evaluated if func1() returned a false value, func2() is not called at all.

You could use a third alternative here using the all() function :

functions = (func1, func2, func3, func4)
if all(f() for f in functions):

which would again only call functions as long as the preceding function returned a true value and call the functions in order.

The all() approach does require that func1 , func2 , func3 , and func4 are all actually defined before you call all() , while the nested if or and expression approaches only require functions to be defined as long as the preceding function returned a true value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM