Conditional operator in Python?

thp at cs.ucr.edu thp at cs.ucr.edu
Tue Sep 4 19:00:10 EDT 2001


Terry Reedy <tjreedy at home.com> wrote:

: <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.

The point is that lambda notation is equally clear to procedural 
notation in this situation, namely:

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

and clearer in others, e.g.:

  y = derivative( ( lambda x: sqrt(3*x) ), at = 4.28 )

Lambda expressions are to functions what literals are to numbers.
Some folks advocate getting rid of literals ("magic numbers") in
complex expressions by assigning them to "meaningful" variables and
using those variables instead.  There are, however, still places where
the use of numeric literals in expressions improves readability.  The
same goes for lambda expressions, including those that involve
selection operations.

Tom Payne



More information about the Python-list mailing list