Conditional operator in Python?

thp at thp at
Tue Sep 4 09:47:31 CEST 2001

Weet Vanniks <Weet.Vanniks at> 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