Short if

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Wed Jul 7 12:20:22 CEST 2004


Sylvain Thenault wrote:
> On Wed, 07 Jul 2004 09:40:04 +0000, Paul Sweeney wrote:
> 
>>> Does Python have a short if like C or PHP:
>>>
>>>   bool = false
>>>   string = 'This is ' + (( bool ) ? 'true' : 'false')
>>>
>>>
>> 
>> If you are really convinced that this is a good road to go down (think of
>> code readability), you could do
>> 
>>     bool = False   # check capitalisation! string = 'This is ' +
>>     ('false','true')[bool]
> 
> you can use logical "and" and "or" to achieve this:
> 
> string = 'This is ' + (bool and 'true' or 'false')

But be warned, if you construct such a thing:

int = 2 + (bool and 0 or 1)

you will get 3 as an answer every time. So if you want to use the
and-or-Form, be sure that the second expression cannot have a false
value (that is, "", [], {}, 0, etc.)

Reinhold

-- 
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich.  Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
  -- David Kastrup in de.comp.os.unix.linux.misc



More information about the Python-list mailing list