UFO ET IT

Python에서 AND 및 NOT 연산자 사용

ufoet 2020. 12. 6. 22:24
반응형

Python에서 AND 및 NOT 연산자 사용


이 질문에 이미 답변이 있습니다.

여기에 삼각형을 나타내는 커스텀 클래스가 있습니다. 나는 여부를 확인하는 것이 코드를 작성하기 위해 노력하고있어 경우 self.a, self.b그리고 self.c내가 각도, 각도, 각도가 있음을 의미하는 0보다 큰.

아래에서 A와 B를 확인하는 코드를 볼 수 있지만 바로 사용하면 self.a != 0정상적으로 작동합니다. 내가 &올바르게 사용 하고 있지 않다고 생각 합니다. 어떤 아이디어? 내가 그것을 부르는 방법은 다음과 같습니다.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에서 "and"입니다.

원하는 것을 확인하는 더 짧은 방법은 "in"연산자를 사용하는 것입니다.

if 0 not in (self.a, self.b) :

"in"을 사용하여 이터 러블의 일부인지 확인할 수 있습니다.

  • 튜플. IE : "foo" in ("foo", 1, c, etc)true를 반환합니다.
  • 기울기. IE : "foo" in ["foo", 1, c, etc]true를 반환합니다.
  • 문자열. IE : "a" in "ago"true를 반환합니다.
  • 딕트. IE : "foo" in {"foo" : "bar"}true를 반환합니다.

의견에 대한 답변 :

예, "in"을 사용하는 것은 Tuple 객체를 생성하기 때문에 느리지 만 실제로 성능은 여기서 문제가되지 않으며 Python에서는 가독성이 매우 중요합니다.

삼각형 검사의 경우 읽기가 더 쉽습니다.

0 not in (self.a, self.b, self.c)

보다

(self.a != 0) and (self.b != 0) and (self.c != 0) 

리팩토링하는 것도 더 쉽습니다.

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.


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

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


It's called and and or in Python.

참고URL : https://stackoverflow.com/questions/1075652/using-the-and-and-not-operator-in-python

반응형