[Tutor] if ... else shorthand form ?

Eric Abrahamsen eric at abrahamsen.com
Sat Feb 9 10:26:56 CET 2008


> Hi all,
>
> Returning to python after a brief affair with C++, I have the  
> following code ...
>
>                if (items.has_keys('snapshot_interval')):
>                    self.snap_init[i] = items['snapshot_interval']
>                else:
>                    self.snap_init[i] = 0
>
> I thought Python had a shorthand version of something like ....
>
>                self.snap_init[i] =
> (items.has_keys('snapshot_interval'))?items['snapshot_interval']:0

I believe the idiom here is

var = value if condition else otherValue

So you'd want

self.snap_init[i] = items['snapshot_interval'] if  
items.has_keys('snapshot_interval') else 0


Yours,
Eric


More information about the Tutor mailing list