Conditional operator in Python?

Terry Reedy tjreedy at home.com
Tue Sep 4 20:19:01 CEST 2001


<thp at cs.ucr.edu> wrote in message
news:mailman.999590706.31784.python-list at python.org...
> which reads better with a couple of if's added:
>
>     p = lambda k, n :
>       if k < 1  or k > n  then
>         0
>       else if n == 1 or n == k then
>         1
>       else
>         p( k-1, n-1 ) + p (k, n-k )
>
> I'm not lobbying for ?: notation in particular.  I simply want
> something better than (a and [b] or [c])[0].  In fact, the
> if/then/else notation is my personal favorite.

So use def/return instead of lambda/whatever

def p(k,n):
  if    k < 1  or k > n: return 0
  elif n == 1 or n == k: return 1
  else: return p( k-1, n-1 ) + p (k, n-k )

This could hardly be any clearer.

Terry J. Reedy







More information about the Python-list mailing list