Ternary Operator in Python

Terry Reedy tjreedy at udel.edu
Fri Apr 1 13:32:21 EST 2005


"praba kar" <prabapython at yahoo.co.in> wrote in message 
news:20050401072442.73412.qmail at web8408.mail.in.yahoo.com...
> Dear All,
>    I am new to Python.  I want to know how to
> work with ternary operator in Python.  I cannot
> find any ternary operator in Python.  So Kindly
> clear my doubt regarding this

A unary operator has one operand; a binary operator has two operands; a 
ternary operator has three operands.  Python has none built-in, although 
one can 'synthesize' all sorts of ternary operators by combining two binary 
operators, with the operand of one being the result of the other.  However, 
people often don't think of such combinations as being such.

Since C has one builtin ternary 'operator' (if-else), the term 'ternary 
operator' is too often used as a synonym for that particular example of a 
ternary operator.  Others have referred you to discussions of if-else 
expressions in Python.

Ironically, if one thinks of or defines an operator as being a function 
called without parenthesis, then C's ';:' and Python's 'and..or' are not 
really ternary operators but flow control expressions equivalent in effect 
to certain if/else statement pairs.  That is because some of the operands 
may not be evaluated.  That is also why there are no special methods 
corresponding to 'and' and 'or'.  They are directly compiled to conditional 
code with no a function call corresponding to the 'operator'.

Terry J. Reedy






More information about the Python-list mailing list