if cpu_expensive_condition() or simple_condition():
do_something()
out of two condition in OR statement in above python code which will be evaluate first ? , and is it compulsory that both will be evaluate ?
Order of Evaluation In Python, the left operand is always evaluated before the right operand. That also applies to function arguments. Python uses short circuiting when evaluating expressions involving the and or or operators.
In an expression, Python interpreter evaluates operators with higher precedence first. And, except the exponent operator (**) all other operators get evaluated from left to right.
The left clause will be evaluated first, and then the right one only if the first one is False . Without it breaking. Conversely, with an and clause, the right clause will only be evaluated if the first one is True : if person and person.name: # ...
Ternary operators are also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
The expression
x or y
first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Quoted from Python Language Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With