Search code examples
pythonif-statementshort-circuiting

One else for multiple if conditions


I created some functions which return 1 if all went well and 0 if there was an error. Now, I need to execute each of these functions in a defined order and verify the return values. If one of them returns 0, I need to reboot immediately, without invoking any of the subsequent functions.

I intended to use multiple ifs but with one else:

if function_1():
    if function_2():
        if function_3():
            print "Everything went well"
else:
    reboot()

but it does not work like I want: I want the else part to be executed right after any of these conditions fails, and now it is executed only if function_1 fails.


Solution

  • There are two ways to do this.

    1). You can use one if statement, and and the conditions together. This will produce "short circuiting" behavior, in that it will continue through the functions until the first one fails, then none of the remaining will execute.

    if function_1() and function_2() and function_3():
        print "Everythings went well"
    else:
        Reboot
    

    2) If you want all to execute, here is a method, though it is more cumbersome.:

    successful = True
    
    successful = successful and function_1()
    successful = successful and function_2()
    successful = successful and function_2()
    
    if successful:
        print "Everythings went well"
    else:
        Reboot