0

I was learning about lambda functions, and saw this example. I cannot understand how, 'odd', or 'even' is selected.

print((lambda x: (x % 2 and 'odd' or 'even'))(3))

returns odd

print((lambda x: (x % 2 and 'odd' or 'even'))(4))

returns even

dKenez
  • 1
  • 2
  • 1
    I didn't know about that but googling it, it Iooks like it is a ShortHand Ternary expression : look at [ShortHand Ternary (at the end)](https://book.pythontips.com/en/latest/ternary_operators.html) – Clément Jan 17 '20 at 14:58
  • Both snippets are the same, they both return `odd`; but that just as an aside…You could type those snippets in little by little and see how they work. What do you get for `1 and 'odd'`? `0 and 'odd'`? – deceze Jan 17 '20 at 15:02
  • 1
    It's a terribly clever (i.e. really bad) way to write `'odd' if x % 2 else 'even'`. – tobias_k Jan 17 '20 at 15:03
  • Thank you all very much! The link proved really helpful. – dKenez Jan 17 '20 at 20:08

0 Answers0