在Python中使用AND和NOT运算符 [英] Using the AND and NOT Operator in Python
问题描述
这是我自定义的类,它代表一个三角形.我正在尝试编写代码以检查self.a
,self.b
和self.c
是否大于0,这意味着我具有Angle,Angle和Angle.
Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if self.a
, self.b
, and self.c
are greater than 0, which would mean that I have Angle, Angle, Angle.
在下面,您将看到检查A和B的代码,但是当我只使用self.a != 0
时,它可以正常工作.我相信我没有正确使用&
.有任何想法吗?这是我的称呼方式:print myTri.detType()
Below you will see the code that checks for A and B, however when I use just self.a != 0
then it works fine. I believe I'm not using &
correctly. Any ideas? Here is how I am calling 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
推荐答案
您应该写:
if (self.a != 0) and (self.b != 0) :
"&
"是按位运算符,不适合布尔运算.在Python中,"&&
"的等效项是和".
"&
" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&
" is "and" in Python.
检查所需内容的一种较短方法是使用"in"运算符:
A shorter way to check what you want is to use the "in" operator :
if 0 not in (self.a, self.b) :
您可以使用"in"检查是否有任何内容是可迭代项的一部分,它适用于:
You can check if anything is part of a an iterable with "in", it works for :
- 组合.即:
"foo" in ("foo", 1, c, etc)
将返回true - 列表.即:
"foo" in ["foo", 1, c, etc]
将返回true - 字符串.即:
"a" in "ago"
将返回true - 词典.即:
"foo" in {"foo" : "bar"}
将返回true
- Tuples. I.E :
"foo" in ("foo", 1, c, etc)
will return true - Lists. I.E :
"foo" in ["foo", 1, c, etc]
will return true - Strings. I.E :
"a" in "ago"
will return true - Dict. I.E :
"foo" in {"foo" : "bar"}
will return true
作为评论的答案:
是的,由于要创建Tuple对象,因此使用"in"的速度较慢,但是实际上性能不是问题,在Python中可读性也很重要.
Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.
对于三角形检查,更容易阅读:
For the triangle check, it's easier to read :
0 not in (self.a, self.b, self.c)
比
(self.a != 0) and (self.b != 0) and (self.c != 0)
重构也更容易.
当然,在此示例中,它并不是那么重要,它是非常简单的代码段.但是,这种风格导致了Python式代码的出现,从而导致大型程序上的程序员更加快乐(减轻体重,改善性生活等).
Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.
这篇关于在Python中使用AND和NOT运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!