(a==b) ? 'Yes' : 'No'

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Apr 2 12:00:47 EDT 2010

On Fri, 02 Apr 2010 07:05:49 -0700, Steve Howell wrote:

>> How is the ternary operator "not really ternary, it's binary"? It
>> requires three arguments, not two, which makes it ternary. In Python
>> syntax:
> Of course, I understand that the ternary operator has three arguments,
> but it only has two possible outcomes.

But the number of outcomes is not what the "binary" in binary operator 
refers to. It's the number of arguments.

> You asked me to elaborate on the "Tyranny of Three."  Let's say you have
> three possible outcomes.
> In some languages you would write something like this:
> mark = (rolls == 1) && (pins == 10) ? 'strike' :
>        (rolls == 2) && (pins == 10) ? 'spare' :
>                                       'normal'

Not if you held a gun to my head *wink*

> Many people consider the above very ugly, so they write it like so:
[snip multiple alternative ways of choosing between three alternatives]

All very interesting, but I don't see why you are singling out three 
alternatives as particularly difficult. Not all choices between three 
possible results are hard to code:

choice = some_integer % 3  # returns 0, 1, or 2.

and choosing between two results isn't necessarily simple either, e.g. 
the rules of protocol. Deciding which of two people outrank the other can 
be *very* complicated. Does a king outrank a pope? What about a 
president? Does a prince of some two-bit speck of dirt outrank a senator 
of a superpower? People have worked out (by which I mean, "made up") 
rules for all these and more, and they still can't always agree on who 
ranks who. International negotiations have floundered and collapsed 
because the parties couldn't agree which ambassador got the chair at the 
head of the table nearest the door...

You are absolutely right to say that some problems don't have an elegant 
solution, but I think you're wrong to single out "three" as special.


More information about the Python-list mailing list