Using the AND and NOT operator in Python

Here is my own class, which I have, which is a triangle. I am trying to write code that checks if self.a , self.b and self.c greater than 0, which means that I have Angle, Angle, Angle.

Below you will see code that checks A and B, however, when I use only self.a != 0 , then it works fine. I believe that I am not using & correctly. Any ideas? This is what I call it: print myTri.detType()

 class Triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f def detType(self): #Triangle Type AAA if self.a != 0 & self.b != 0: return self.a #If self.a > 10: #return AAA #Triangle Type AAS #elif self.a = 0: #return AAS #Triangle Type ASA #Triangle Type SAS #Triangle Type SSS #else: #return unknown 
+49
operators python
Jul 02 '09 at 17:22
source share
3 answers

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.

+96
Jul 02 '09 at 17:34
source share

Use the and keyword and not & , because & is a bit operator.

Be careful with this ... so that you know that in Java and C ++, the & operator is ALSO a bit operator. The correct way to make logical comparisons in these languages ​​is && . Similarly | is a bit operator, and || is a boolean operator. In Python, and and or are used for boolean comparisons.

+20
Jul 02 '09 at 17:27
source share

He called and and or in Python.

+8
Jul 02 '09 at 17:27
source share



All Articles