Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python Check ALL conditions in an multi-condition if statement? [duplicate]

I am curious if Python will continue checking conditions in an if statement if the first condition returns False. I'm wondering about this because I want to know if best practice is try to check conditions with low time-complexity before more complex checks.

Is there any difference between these two snippets?

if condition_1() and condition_2():
    do_something()

and

if condition_1():
    if condition_2():
        do_something()
like image 903
Joseph Avatar asked Jul 02 '26 18:07

Joseph


1 Answers

Yes, python boolean operators do short-circuit

Both code samples are semantically equivalent, but the first is more readable, as it has lower level of nesting.

like image 177
SergeyA Avatar answered Jul 04 '26 08:07

SergeyA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!