Question About Logic In Python

sven ml.sven at subscience.de
Mon Sep 19 12:16:15 CEST 2005


At 02:20 19.09.2005, James H. wrote:
>Greetings!  I'm new to Python and am struggling a little with "and" and
>"or" logic in Python.  Since Python always ends up returning a value
>and this is a little different from C, the language I understand best
>(i.e. C returns non-zero as true, and zero as false), is there anything
>I should be aware of given Python's different approach?  Namely any
>pitfalls or neat tricks that make the Python approach cool or save my
>butt.

to make sure that an operation yields a boolean value wrap a bool() 
around an expression.
None, 0 and objects which's len is 0 yield False.
so you can also do stuff like that:

 >>> a = []
 >>> b = [1,2,3]
 >>> a or b
[1, 2, 3]

 >>> class Foo:
...     def __len__(self): return 0
...
 >>> class Bar:
...     def __len__(self): return 1
...
 >>> foo = Foo()
 >>> bar = Bar()
 >>> foo or bar
<__main__.Bar instance at 0x7D289940>

sven. 




More information about the Python-list mailing list