if the else short form

Philip Semanchuk philip at semanchuk.com
Wed Sep 29 14:53:17 CEST 2010


On Sep 29, 2010, at 7:19 AM, Tom Potts wrote:

> This is just a sneaky shorthand, which is fine if that's what you want, but
> it makes it harder to read.  The reason it works is that 'fill==True' is a
> boolean expression, which evaluates to True or False, but if you force a
> True into being an integer, it will be 1, and a False will become 0.  Try
> writing 'True == 1' on the Python interpreter to see what I mean.  So this
> code snippet is creating a tuple with two elements, and then selecting the
> first if 'fill==True' is False, or 0, and selecting the second if
> 'fill==True' is True, or 1.
> 
> As I say, this kind of coding is absolutely fine, but it makes things harder
> to read and doesn't really save much space.  I wouldn't recommend using this
> kind of style yourself, at least until you're more familiar with programming
> in Python.

Does Python make any guarantee that int(True) == 1 and int(False) == 0 will always hold, or are their values an implementation detail?

Thanks
Philip


> On 29 September 2010 11:42, Tracubik <affdfsdfdsfsd at b.com> wrote:
> 
>> Hi all,
>> I'm studying PyGTK tutorial and i've found this strange form:
>> 
>> button = gtk.Button(("False,", "True,")[fill==True])
>> 
>> the label of button is True if fill==True, is False otherwise.
>> 
>> i have googled for this form but i haven't found nothing, so can any of
>> you pass me any reference/link to this particular if/then/else form?
>> 
>> thanks
>> Nico
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list