Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - if statements containing multiple boolean conditions - how is flow handled?

I'm curious about how Python handles "if" statements with multiple conditions. Does it evaluate the total boolean expression, or will it "break" from the expression with the first False evaluation?

So, for example, if I have:

if (A and B and C):
   Do_Something()

Will it evaluate "A and B and C" to be True/False (obviously), and then apply the "if" to either enter or not enter Do_Something()?, or will it evaluate each sequentially, and if any turn out to be false it will break.

So, say A is True, B is False.

Will it go: A is true --> keep going, B is false - now break out and not do Do_Something()?

The reason I ask is that in the function I'm working on, I've organised A, B, and C to be functions of increasing computational load, and it (of course) would be a complete waste to run B and C if A is False; and equally C is A is True and B is False). Now, of course, I could simple restructure the code to the following, but I was hoping to use the former if possible:

if (A):
 if (B):
   if (C):
     Do_Something()
  

Of course, this equally applies to while statements as well.

Any input would be greatly appreciated.

like image 959
David Galea Avatar asked Mar 12 '26 08:03

David Galea


2 Answers

It's the latter.

if A and B and C:
    Do_Something()

is equivalent to

if A:
    if B:
        if C:
            Do_Something()

This behavior is called short-circuit evaluation.

like image 138
yuri kilochek Avatar answered Mar 13 '26 23:03

yuri kilochek


I think when you think about it this way, you will learn an important concept that you will see all the time:

In a boolean expression you often write something like this:

if (x not None and x.hasValue) 

to protect yourself from an error when: x = None. Because None.hasValue makes no sense. Python knows that when the first value is False, the expression will always be False and hence avoids the computation of the second value.

So the expressions are always evaluated from left to right (otherwise you would get an error when x = None in the above example.

like image 29
Stefan Avatar answered Mar 13 '26 22:03

Stefan



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!