You must write:
if (self.a != 0) and (self.b != 0) :
" & " is a bit wise operator and is not suitable for boolean operations. The equivalent of " && " is "and" in Python.
A shorter way to check what you want is to use the in operator:
if 0 not in (self.a, self.b) :
You can check if something is part of iterable with "in", it works for:
- tuples. IE:
"foo" in ("foo", 1, c, etc) will return true - Lists. IE:
"foo" in ["foo", 1, c, etc] will return true - Strings. IE:
"a" in "ago" will return true - Dict. IE:
"foo" in {"foo" : "bar"} will return true
In response to the comments:
Yes, using "in" is slower since you are creating a Tuple object, but in fact performance is not a problem here, plus readability is of great importance in Python.
To test a triangle it is easier to read:
0 not in (self.a, self.b, self.c)
Than
(self.a != 0) and (self.b != 0) and (self.c != 0)
It is easier to refactor.
Of course, in this example, this is really not so important, this is a very simple fragment. But this style leads to the Pythonic code, which leads to a happier programmer (and lose weight, improve sex life, etc.) in large programs.
e-satis Jul 02 '09 at 17:34 2009-07-02 17:34
source share