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 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 you want to share more information about the topic discussed above.
- Looping Techniques in Python
- Python | Thresholding techniques using OpenCV | Set-2 (Adaptive Thresholding)
- Python | Thresholding techniques using OpenCV | Set-3 (Otsu Thresholding)
- Python | Thresholding techniques using OpenCV | Set-1 (Simple Thresholding)
- Feature Extraction Techniques - NLP
- Types of Regression Techniques
- Scala short ==(x: Int): Boolean
- Long Short Term Memory Networks Explanation
- Text Generation using Recurrent Long Short Term Memory Network
- Python | Convert list to Python array
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- MySQL-Connector-Python module in Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
Improved By : nidhi_biet