[Tutor] am I missing another simpler structure?
Juan Shen
orion_val at 163.com
Thu Dec 16 14:42:06 CET 2004
Kent, Bingle!
Python's 'and' and 'or' operation only returns the right value (any kind
of value: integer, string, list, excuting a function and so on) not
Boolean value (True or False). It's a real fuzzy tip for beginners.
See Chapter 4.6 of Dive into Python for futher reading
Juan Shen
Kent Johnson wrote:
> It's probably worth pointing out that these two functions are not
> entirely equivalent:
> def t1():
> if condition:
> return True
> return False
>
> def t2():
> return condition
>
> because 'condition' does not have to evaluate to a boolean value, it
> can be any Python value.
>
> Here is a simple example where 'condition' is just the value of a
> parameter:
> >>> def t1(a):
> ... if a:
> ... return True
> ... return False
> ...
> >>> def t2(a):
> ... return a
> ...
>
> If a is actually True or False these two functions return the same value:
> >>> a=True; print t1(a), t2(a)
> True True
> >>> a=False; print t1(a), t2(a)
> False False
>
> For other values of a they return different values; t1 will always
> return True or False, while t2, obviously, returns a:
> >>> a=1; print t1(a), t2(a)
> True 1
> >>> a=None; print t1(a), t2(a)
> False None
> >>> a=[]; print t1(a), t2(a)
> False []
>
> Usually this is fine; code such as
> if t1(a): print 'a is True'
>
> will work the same with t1 or t2. OTOH, if you explicitly test the
> return value (which is *not* recommended practice), you will get
> different results:
> >>> if t1(100) == True: print '100 is True'
> ...
> 100 is True
>
> >>> if t2(100) == True: print '100 is True'
> ...
> (nothing prints)
>
> I recommend *not* testing explicitly for True, and I recommend the
> t2() form. Then Python will do what you expect. But I thought it was
> worth pointing out the difference.
>
> Kent
>
> Gregor Lingl wrote:
>
>>
>>
>> Brian van den Broek schrieb:
>>
>>> If my original bit of code, the structure was like:
>>>
>>> output_value = False
>>> if condition:
>>> output_value = True
>>> return output_value
>>>
>>> Mine would be like yours if transformed to:
>>>
>>> if condition:
>>> return True
>>> return False
>>>
>>
>> Hi Brian!
>> Do you mean, that condition is something which is
>> True od False?
>> And if condition is True you want to return True?
>> And if condition is False you want to return False?
>>
>> So why not simlpy:
>>
>> return condition
>>
>> ?
>>
>> Regards,
>> Gregor
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More information about the Tutor
mailing list