Issue
I have been going through a tutorial on lambda functions and came across this line of code to evaluate if a number is odd or even. And I do not understand how the tow logic operators work in this function.
(lambda x: (x % 2 and 'odd' or 'even'))(5)
'odd'
A more "usual/readable" way of doing it might be:
(lambda x: 'even' if x % 2 == 0 else 'odd')(3)
'odd'
I do understand that x % 2 will return either 1 or 0 (truthy or falsey) and based on that the ensuing logic will work. What I do not understand is how the output of x % 2 is then used in the body of the function and how it computes if it is 'odd' or 'even' that is returned. It might have something to do with the priority of Pythonic operators but so far it is not very clear. Any help will be much appreciated.
Solution
General Rule
In Python, conjunctions (stuff joined with 1 or more and
) and disjunctions (or
) evaluate to the last operand that needs to be evaluated to determine the truthiness of the whole expression.
If there is no short-circuit operand, that is the last operand of the expression.
Conjunctions
For and
, this determining operand is the first falsy operand (after which it is clear that the whole expression will falsy).
Disjunctions
For or
, this determining operand is the first truthy operand (after which it is clear that the whole expression will truthy).
Your case:
The expression in your example is scoped:
(n % 2 and "odd") or "even"
Odd:
(1 and "odd") or "even"
# conj: both operands truthy, so the last one is taken
"odd" or "even"
# disj: first operand is truthy, so short-circuit
"odd"
Even:
(0 and "odd") or "even"
# conj: first operand is falsy, so short-circuit
0 or "even"
# disj: first operand falsy, so last operand is taken regardless of its value
"even"
Answered By - user2390182
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.