Conditional Expressions in Python 2.4

Steven Bethard steven.bethard at gmail.com
Fri Jun 2 20:21:08 CEST 2006


A.M wrote:
 > Do we have the conditional expressions in Python 2.4?

bruno at modulix wrote:
> No, AFAIK they'll be in for 2.5

Yep:

Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit 
(Intel)] on win32
 >>> "Yes" if 1 == 1 else "No"
'Yes'

> In the meanwhile, there are (sometime trickyà ways to get the same result:
> 
> a = 1 == 1 and "Yes" or "No"
> a = ("No", "Yes")[1 == 1]


And just to give some examples where the conditional expression will 
show a difference::

 >>> True and 0 or []
[]
 >>> 0 if True else []
0

 >>> def f():
...     print "don't evaluate me"
...     return 'f'
...
 >>> def g():
...     return 'g'
...
 >>> (f(), g())[True]
don't evaluate me
'g'
 >>> g() if True else f()
'g'


STeVe



More information about the Python-list mailing list