Conditional operator in Python?

Sheila King sheila at spamcop.net
Sat Mar 31 21:37:30 EST 2001


On Sat, 31 Mar 2001 18:04:40 -0800, Erik Max Francis <max at alcyone.com> wrote
in comp.lang.python in article <3AC68CB8.22AAF7B8 at alcyone.com>:

:Why isn't there a conditional operator (a ? b : c) in Python? 

This can be implemented in Python by using the 'and' and 'or' operators. I
wish I could remember where I saw the explanation, but I can't remember
whether it was in Chun's _Core Python Programming_ or the "Dive Into Python"
website. In any case, I can't find it right now.

>From Kernighan and Ritchie, page 51:

"""
The <i>conditional experssion<i>, written with the ternary operator "?:",
provides an alternate way to write this and similar constructions. In the
expression
	expr1 ? expr2 : expr3

the expression expr1 is evaluate first. If it is non-zero (true), then the
expression expr2 is evaluated, and that is the value of the conditional
expression. Otherwise, expr3 is evaluated, and that is the value. Only one of
expr2 and expr3 is evaluated. Thus to set z to the maximum of a and b,
	z = ( a > b ) ? a : b;  /* z = max(a,b) */
"""

I'm sure I saw this on the "Dive into Python" site...? (Ok, I finally found
the reference, here:
http://diveintopython.org/apihelper_andor.html  )
How can we do this in Python using 'and' and 'or'...

in Python:
a and b   returns the value of b if a is true, else returns the value of a
a or b    returns the value of a if a is true, else returns the value of b

So, to return the max of a or b I could do

return  ( a > b ) and a or b

Here is an interpreter session:

>>> a = 5
>>> b = 3
>>> (a > b) and a or b
5
>>> a = 2
>>> b = 12
>>> (a > b) and a or b
12
>>> 

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/

: 2.0 now
:has augmented assignments, and the FAQ even acknowledges that the
:conditional operator is sometimes quite convenient and gives some (very
:awkward) Python alternatives.
:
:I've been reading comp.lang.python for a while (since just before 2.0
:shipped) and I can't really remember much discussion about it.  Is it a
:perennial request and I'm just missing it?




More information about the Python-list mailing list