Conditional operator in Python?

thp at cs.ucr.edu thp at cs.ucr.edu
Tue Sep 4 03:47:31 EDT 2001


Weet Vanniks <Weet.Vanniks at el_simpatico.be> wrote:
: What about :

: def cond_choose(cond,first_choice,second_choice):
:      if cond:
:           return first_choice
:      return second_choice

: whatever= cond_choose(x,a,b)

: This seems much cleaner to me than all those contorsions with the syntax.

I agree that it's cleaner, but unfortunately it doesn't work.  Try

  factorial = lambda x : cond_choose( x<=1, 1, x*factorial(x-1) )

for example.  It overflows the stack without ever invoking cond_choose.
The problem is that we need short-circuiting evaluation.  When x<=1,
we must not evaluate factorial(x-1).

Tom Payne



More information about the Python-list mailing list