VB’s iif in Python
Here you go:
def iif(condition,resultiftrue,resultiffalse):
if condition:return resultiftrue
else: return resultiffalse
#usage: furrycoat=iif(is_summer==True,”light coat”,”Heavy coat”)
It’s very simple I know, probably not worthy of posting, however a search for “python iif” returned nothing useful, and some misleading answers. And my philosophy is to post anything I search for and the answer isn’t readily available.






September 20th, 2005 at 1:23 pm
I’ve taken to using an even simpler, if not quite as easy to follow, construct:
value = boolean and truevalue or falsevalue
So, in your example:
furrycoat = is_summer and “light coat” or “Heavy coat”
September 20th, 2005 at 2:01 pm
furrycoat = is_summer and “light coat” or “Heavy coat”
That looks like a good idea. I’m not sure why it works offhand. The benefit to that it should short-circuit, whereas my iif evaluates all of the arguments. I’ll give that a try.
September 20th, 2005 at 2:21 pm
It appears to work because it’s just simple logic; I tested it extensively when I first came up with it and it does appear to work exactly as you’d expect. Probably a case of “naw, that’s too simple, it can’t work!”.
I had been looking for an analogy to the PHP/C ‘value = boolean ? truevalue : falsevalue;’ which is yet another way of expressing the same thing.
September 20th, 2005 at 3:55 pm
It’s not the same thing. “a ? b : c” or “iif(a, b, c)” will return b if a is true and b is not true. “a and b or c” will only return b if both a and b are true. This is a common mistake for people trying to get clever with Python syntax. You could use “(a and [b] or [c])[0]” or simply write it out:
if a:
val = b
else:
val = c
September 20th, 2005 at 11:11 pm
Figures
September 21st, 2005 at 3:12 am
just for fun..
tuple/array-assignment
#int(True)==1,int(False)==0
furrycoat = (’light coat’,'heavy coat’)[int(is_summer)]
September 21st, 2005 at 9:54 am
tuple/array-assignment
#int(True)==1,int(False)==0
furrycoat = (’light coat’,’heavy coat’)[int(is_summer)]
This looks promising.
September 21st, 2005 at 1:31 pm
Please consider readability. Some code is just one-off that never gets read by another person - like in the interactive python shell. If you want to save a couple line breaks in such a rare situation, by all means use your method.
However this conditional assignment has been rejected for inclusion in python proper partly because it is so unreadable.
if is_summer:
furrycoat = ‘light coat’
else:
furrycoat = ‘heavy coat’
Is, IMHO, the best way to do it.
October 31st, 2005 at 11:39 pm
Why don’t they just include the C-style ?: expressions? Everyone can read them, you save the linebreaks for simple expressions, it’s win-win!
August 18th, 2006 at 10:22 am
@mm: wrong!
(’heavy coat’, ‘light coat’)[int(is_summer)]
but thanks for the tip…