Conditional Expressions in Python 2.4

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri Jun 2 19:38:55 EDT 2006


Steven Bethard a écrit :
> A.M wrote:
>  > Do we have the conditional expressions in Python 2.4?
> 
> bruno at modulix wrote:
> 
(snip)
> 
>> 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 []
> []

Yes, this is one of the tricky part !-)
<op>
Always make sure the second term doesn't eval to False.
</op>

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

Why on earth are you calling the callables *before* testing ?
Should be:

(f, g)[True]()

of course.



More information about the Python-list mailing list