Conditional operator in Python?

thp at cs.ucr.edu thp at cs.ucr.edu
Tue Sep 4 18:41:16 CEST 2001


Marcin 'Qrczak' Kowalczyk <qrczak at knm.org.pl> wrote:
: Tue, 04 Sep 2001 08:15:12 -0700, Erik Max Francis <max at alcyone.com> pisze:

:>> I think (though it would need a bit of careful checking) that
:>> there is no conflict with the existing Python syntax in making
:>> 
:>>         if <expr> then <expr> else <expr>
:>> 
:>> an expression.
:>> 
:>> Perhaps adding this to the syntax could be a PEP?
:> 
:> That seems pretty reasonable to me.  I've been itching for
:> a conditional operator in Python for quite some time.

: The biggest problem is that 'then' is not currently a keyword.

So, following accepted Python syntax, let's replace it with ":",
obtaining, for instance:

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

or, perhaps:

  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)

which can be folded as follows:

  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)

Tom Payne






More information about the Python-list mailing list