1

simplified example:

a = False
b = True

if a and b:
    #do stuff

Does python skip checking for b if a is already recognized as false because only one condition needs to be False for the whole statement to be False?

In my case i want to check an array for 3 conditions but want to stop if at least one of them is false (for a better runtime). Can i do

if a and b and c:
    #do stuff

or do i have to go the long way with

if a:
    if b:
        if c:
            return True
        else:
            return False
     else:
         return False
 else: 
     return False

or is there another way to check stuff like this?

Proxycon
  • 71
  • 7

2 Answers2

2

Yes, Python short-circuits.

Proof:

>>> int('ValueError')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'ValueError'
>>> 
>>> False and int('ValueError')
False
>>> True or int('ValueError')
True
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

Yes, what you described above is called short circuiting and python does do that.

Similar is the case with or operation.

a or b

is short circuited at a if a is True otherwise b is checked.

penguin2048
  • 1,303
  • 13
  • 25