Short Circuiting Techniques in Python
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.
The chart given below gives an insight of the short circuiting of in case of boolean expressions. Boolean operators are ordered by ascending priority.
or: When the Python interpreter scans or expression, it takes 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 checks the second value and then result is based on 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, it checks the second statement and returns the value.
An expression containing and and or stops execution when the truth value of expression has been achieved. Evaluation takes place from left to right.
geeks 1 geeks 1
Inbuilt functions all() and any() in python also support short-circuiting. Example below would give you clear insight on how it works.
geeks geeks geeks False geeks geeks geeks geeks True
Conditional operators also follow short circuiting as when expression result is obtained, further execution is not required.
False geeks True geeks False
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course