Question About Logic In Python
Ron Adam
rrr at ronadam.com
Wed Sep 21 14:53:34 EDT 2005
Steven D'Aprano wrote:
>>So..
>>
>> bool(a and b) * value
>>
>>Would return value or zero, which is usually what I want when I do this
>>type of expression.
> That's all very interesting, and valuable advice for somebody who doesn't
> understand how Python's logical operators work, but the question is, when
> would you actually want that type of expression?
It's a filter which returns a value or zero depending on conditions a and b.
Some examples...
High pass filter:
(value > 0) * value
Low pass filter:
(value < 0) * value
Band pass filter:
(min < value < max) * value
Changing and and or to return bools only, doesn't prevent us from doing
anything we can already do. It just means changing the context to
explicitly return a non bool when you want one as I did here.
> In practice, how often do you really care that your truth values have the
> specific values 0 and 1 rather than anything false and anything true? In
> what circumstances?
We can separate these into two groups...
1. True and false condition testing in which the result of the
condition is not used in any further expressions.
You are correct in this case, it doesn't matter. Any True values would work.
2. Expressions that will be used in a calculation or another
expression.
This matters because if you aren't careful your results may not be what
you expect.
But group (2) can also be a part of group (1). So then again it may
matter there too.
This has more to do with clarity and separating function into forms that
have the potential for least surprises. Or to put it another way, forms
that are predictable with no exceptional circumstances.
In boolean math it is useful to add and subtract.
>>> a = b = True
>>> a + b
2 # Non boolean result.
>>> True * True
1 # Why not return True here as well?
This is like adding two integer types and getting a float.
There's the possibility of adding two (normally) True values and getting
a False result.
>>> a = True
>>> b = -1
>>> a + b # True_value + True = False_value
0
Should bool type act like bools as expressed here?
http://www.ee.surrey.ac.uk/Projects/Labview/boolalgebra/
# P1: X = 0 or X = 1
# P2: 0 . 0 = 0
# P3: 1 + 1 = 1
# P4: 0 + 0 = 0
# P5: 1 . 1 = 1
# P6: 1 . 0 = 0 . 1 = 0
# P7: 1 + 0 = 0 + 1 = 1
Table 1: Boolean Postulates
Python's bools work this way if you use 'and' and 'or' and always cast
any non bools to bools first. But it would be easier IMO if bool
operations gave bool results so I wouldn't need to do:
bool_result = a and bool(b)
or
bool_result = bool(a and b)
On one hand these seem like little things, but little things is
sometimes what will bite you the hardest as they are more likely to get
by your guard.
Cheers,
Ron
More information about the Python-list
mailing list