One else for multiple if conditions

Dam*_*got -1 python if-statement short-circuiting

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()
Run Code Online (Sandbox Code Playgroud)

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.

Cor*_*mer 7

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,人们对一个不明确的问题的答案进行了贬低和狡辩,而不是低估问题,并投票将其关闭,因为不清楚. (6认同)
  • 如果您希望任何函数的短路行为失败,那么这将起作用,但如果您需要确保调用每个函数,则不行. (3认同)
  • 不知道为什么这会有一个downvote - 似乎这个解决方案与OP相同 - 即使是在快捷方式方面. (2认同)
  • 如果`function_1()`失败,则不执行其他功能.我认为这不是预期的行为. (2认同)
  • SO引擎非常善于发现这种行为并将其逆转. (2认同)