1

I came across the below expression in python to evaluate if a number is odd or even. While it looks elegant I was surprised to see it work. I guess for the input 3: x%2 equals 1 which evaluates to True and non-empty strings (odd) evaulate to True. So we have True and True or <don't have to check because it doesn't matter if True or False as the overall statement will be True>. But why is the output in that case not True but odd - what concept do I miss?

>>> (lambda x:
... (x % 2 and 'odd' or 'even'))(3)
'odd'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

The and and or operators are not limited to True and False; they return one of their operands.

>>> 1 and "odd"
'odd'
>>> 0 or "even"
'even'
Joni
  • 108,737
  • 14
  • 143
  • 193