Short Circuiting Techniques in Python
Last Updated :
15 May, 2022
By short-circuiting, we mean the stoppage of execution of boolean operation if the truth value of expression has been determined already. The evaluation of expression takes place from left to right. In python, short-circuiting is supported by various boolean operators and functions.
Short-Circuiting in Boolean Operators
The chart given below gives an insight into the short-circuiting case of boolean expressions. Boolean operators are ordered by ascending priority.
or: When the Python interpreter scans or expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object’s value without checking the second statement. The program does not bother with the second statement. If the first value is false, only then Python check the second value, and then the result is based on the second half.
and: For an and expression, Python uses a short circuit technique to check if the first statement is false then the whole statement must be false, so it returns that value. Only if the first value is true, does it check the second statement and return the value.
An expression containing and or stops execution when the truth value of expression has been achieved. Evaluation takes place from left to right.
Python3
def check():
return "geeks"
print ( 1 and check())
print ( 1 or check())
print ( 0 or check() or 1 )
print ( 0 or check() and 1 )
|
Short-Circuiting in all() and any()
Inbuilt functions all() and any() in python also support short-circuiting. The example below would give you clear insight into how it works.
Python3
def check(i):
print ( "geeks" )
return i
print ( all (check(i) for i in [ 1 , 1 , 0 , 0 , 3 ]))
print ( "\r" )
print ( any (check(i) for i in [ 0 , 0 , 0 , 1 , 3 ]))
|
Output
geeks
geeks
geeks
False
geeks
geeks
geeks
geeks
True
Short-Circuiting in conditional operators
Conditional operators also follow short-circuiting as when expression result is obtained, further execution is not required.
Python3
def check(i):
print ( "geeks" )
return i
print ( 10 > 11 > check( 3 ) )
print ( "\r" )
print ( 10 < 11 > check( 3 ) )
print ( "\r" )
print ( 10 < 11 > check( 12 ) )
|
Output
False
geeks
True
geeks
False
Short-circuiting in a ladder of if, elif, elif, … else statements
When there is a sequence, aka a “ladder” of if and one or more elif statements, none of the conditions after the first one found to be True are evaluated.
Python3
a = 10
b = 20
c = 30
def printreturn(l):
print (l)
return l
if a = = 11 :
print ( "a == 11" )
elif b = = 20 and c = = 30 :
print ( "b==20 and c==30" )
elif b = = a + a and 0 < len (printreturn( "This was evaluated" )):
print ( "b == a+a" )
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...