"?:", "a and b or c" or "iif"

Graham Matthews graham at sloth.math.uga.edu
Tue May 25 13:44:52 EDT 1999


news.eunet.no (Hans-Christian.Holm at nrk.no) wrote:
: Python uses :, but what about a builtin "iif"? This function exists in other
: languages, and is easy to implement:
: 
: def iif(x, a, b):
:   if x:
:     return a
:   else:
:     return b
: 
: I use it quite often, as it does make the code a lot cleaner when the
: functionality is needed many times in a program. 

But the above code is not equivalent to a "condt ? a : b" construct
as you suggested. Why? Your "iif" function evaluates both "a" and "b"
since function arguments are evaluated before function calls. The "?"
construction only evaluates one of "a" and "b". 

graham

-- 
               Black velvet in that little boy's smile
                 Black velvet and a soft southern sky
            A new religion that'll bring you to your knees
                     Black velvet, if you please




More information about the Python-list mailing list