Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

New to Python and it’s been a long time since I’ve done any serious coding. 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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, C to be functions of increasing computational load and it (of course) would be a complete waste to run B, 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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading