1
>>> def accept(d1, d2):
    if somefunc(d1,d2) > 32:
        h = 1
    else:
        h = 0
    return h

Does Python have a ternary conditional operator? doesn't give a solution for a case one want to return a value. A lambda based solution is preferable.

Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245

3 Answers3

5

The "return-value scenario" is no different than any other:

return 1 if somefunc(d1, d2) > 32 else 0

If for some reason you want a lambda:

lambda d1, d2: 1 if somefunc(d1, d2) > 32 else 0

Note that a lambda is no different than a function defined with def that returns the same thing. Lambdas are just regular functions.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
3

Or, perhaps trickier,

return int(somefunc(d1, d2) > 32)

Note that int(True) == 1 and int(False) == 0.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
  • Actually you could just return `somefunc(d1, d2) > 32` directly, since True and False already are `int`s. – BrenBarn Oct 06 '13 at 21:13
  • 1
    But that wouldn't return **exactly** what their original code returned. For all we know, someone on the receiving end is doing a `type()` check on the results ;-) – Tim Peters Oct 06 '13 at 21:14
-1

Turn into a lambda (not a explicit function):

accept = lambda d1,d2: 1 if somefunc(d1, d2) > 32 else 0
Nacib Neme
  • 859
  • 1
  • 17
  • 28