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 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.
geeks 1 geeks 1
Inbuilt functions all() and any() in python also support short-circuiting. The example below would give you clear insight into 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
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.
b==20 and c==30
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.