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.
- Python PIL | BoxBlur() method
- Python | sympy.ones() method
- Python | sympy.zeros() method
- Python | sympy.eye() method
- How to write an empty function in Python - pass statement?
- Operator Functions in Python | Set 2
- Time Functions in Python | Set-2 (Date Manipulations)
- Send mail from your Gmail account using Python
- Python – The new generation Language
- Print Single and Multiple variable in Python
- Increment and Decrement Operators in Python
- str() vs repr() in Python
- Swap two variables in one line in C/C++, Python, PHP and Java
- Generate all permutation of a set in Python
- Class or Static Variables in Python
Improved By : nidhi_biet