[Tutor] how to wirte code In python :str = (a>b?"Yes":"NO")

Kent Johnson kent37 at tds.net
Fri Feb 16 15:32:59 CET 2007


Michael P. Reilly wrote:
> Before 2.5, you could generally write:
> 
> str = (a > b) and "Yes" or "No"

With a significant gotcha that you should definitely understand before 
you use this. For example this will not work as expected:
s = (a > b) and "" or "No"

In [1]: s = True and "" or "No"

In [2]: s
Out[2]: 'No'

because True and "" will always be False.

http://www.effbot.org/pyfaq/is-there-an-equivalent-of-c-s-ternary-operator.htm

Kent



More information about the Tutor mailing list