파이썬의 논리 연산자 and, or, not (논리적 결합, 분리, 부정)

사업

Python은 논리(부울) 연산을 수행하기 위한 논리 연산자를 제공합니다.(and,or,not)
if 문에서 여러 조건 간의 관계를 설명하는 데 사용됩니다.

이 섹션에서는 다음에 대해 설명합니다.

  • 교차로:and
  • 논리적 추가:or
  • 부정:not
  • and,or,not연산자 우선순위

또한 다음 사항을 주의 사항으로 설명합니다.

  • bool이 아닌 유형의 객체에 대한 논리 연산자
  • and,or이러한 반환 값은 반드시 bool 유형일 필요는 없습니다.
  • 단락(단락 평가)

교차로:and

두 값의 논리적 곱을 반환합니다.

print(True and True)
# True

print(True and False)
# False

print(False and True)
# False

print(False and False)
# False

사실 참이나 거짓이 아닌 비교 연산자를 사용하는 조건식에 자주 사용됩니다. 참고로 비교 연산자는 다음과 같습니다.

  • <
  • >
a = 10
print(0 < a)
# True

print(a < 100)
# True

print(0 < a and a < 100)
# True

그리고 다음과 같이 연결될 수 있습니다.

print(0 < a < 100)
# True

논리적 추가:or

또는 두 값의 논리적 OR을 반환합니다.

print(True or True)
# True

print(True or False)
# True

print(False or True)
# True

print(False or False)
# False

부정:not

not”은 값의 부정을 반환하고 true와 false는 반대입니다.

print(not True)
# False

print(not False)
# True

and,or,not연산자 우선순위

이러한 논리 연산자의 우선 순위는 다음과 같습니다. not이 가장 높습니다.

  1. not
  2. and
  3. or

다음 샘플 코드에서 위의 식은 아래에 있는 것처럼 해석됩니다. 추가 괄호는 문제가 없으므로 이 예와 같은 경우에 괄호를 명확하게 설명하는 것이 더 쉬울 수 있습니다.

print(True or True and False)
# True

print(True or (True and False))
# True

and 이전에 연산을 하려면 괄호()를 사용하세요.

print((True or True) and False)
# False

<,>이러한 비교 연산자는 not보다 훨씬 높은 우선 순위를 갖습니다. 따라서 위의 예와 같이 각 비교 작업에 괄호가 필요하지 않습니다.

print(0 < a and a < 100)
# True

Python의 연산자 우선 순위에 대한 요약은 아래 공식 문서를 참조하십시오.

bool이 아닌 유형의 객체에 대한 논리 연산자

With these logical operators, not only bool types (true, false), but also numbers, strings, lists, etc. are processed as boolean values.

다음 객체는 Python의 논리 연산에서 false로 간주됩니다.

  • false로 정의된 상수:None,false
  • 숫자 유형의 0:0,0,0j,Decimal(0),Fraction(0, 1)
  • 빈 시퀀스 또는 컬렉션:',(),[],{},set(),range(0)

다른 모든 값은 true로 간주됩니다.

bool() 함수는 객체의 부울 값을 얻는 데 사용할 수 있습니다. 문자열 ‘0’ 또는 ‘False’는 true로 간주됩니다.

print(bool(10))
# True

print(bool(0))
# False

print(bool(''))
# False

print(bool('0'))
# True

print(bool('False'))
# True

print(bool([]))
# False

print(bool([False]))
# True

문자열의 ‘0’ 또는 ‘false’를 false로 처리하려면 distutils.util.strtobool()을 사용합니다.

and,or이러한 반환 값은 반드시 bool 유형일 필요는 없습니다.

다음은 숫자 값에 대한 각 연산자의 결과를 보여주는 bool 유형이 아닌 객체의 예입니다.

x = 10  # True
y = 0  # False

print(x and y)
# 0

print(x or y)
# 10

print(not x)
# False

위의 예제에서 볼 수 있듯이 Python에서 and/는 bool 유형의 true 또는 false를 반환하지 않지만 true 또는 false인지 여부에 따라 왼쪽 또는 오른쪽 값을 반환합니다. 예제는 숫자이지만 문자열 및 목록과 같은 다른 유형에도 동일하게 적용됩니다. 덧붙여서 not은 bool 유형의 true 또는 false를 반환합니다.

and and or의 반환값에 대한 정의는 다음과 같다.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

6.11. Boolean operations — Expressions — Python 3.10.1 Documentation

좌우 식의 값이 각각 true와 false일 때 반환값을 이해하기 쉽습니다. 반면 둘 다 참이거나 둘 다 거짓이면 순서에 따라 반환 값이 달라집니다.

if 문 등에서 조건식으로 사용하면 결과가 boolean 값으로 판단되어 처리되기 때문에 걱정할 필요는 없으나 추후 처리를 위해 반환값을 사용한다면 조심할 필요가 있습니다.

x = 10  # True
y = 100  # True

print(x and y)
# 100

print(y and x)
# 10

print(x or y)
# 10

print(y or x)
# 100
x = 0  # False
y = 0.0  # False

print(x and y)
# 0

print(y and x)
# 0.0

print(x or y)
# 0.0

print(y or x)
# 0

print(bool(x and y))
# False

true 또는 false로 처리하려면 마지막 예제와 같이 하면 됩니다.
bool(x and y)

및 및 또는의 반환 값은 아래 표에 요약되어 있습니다.

xyx and yx or y
truefalseyx
falsetruexy
truetrueyx
falsefalsexy

단락(단락 평가)

위의 표에서 알 수 있듯이 x와 y에서 x가 거짓이거나 x 또는 y에서 x가 참이면 y의 값에 관계없이 반환 값은 x가 됩니다.

이 경우 y는 평가되지 않습니다.

and,or이러한 프로세스의 오른쪽에 있는 함수나 메서드를 호출하여 일부 처리를 수행하면 왼쪽의 결과에 따라 프로세스가 실행되지 않을 수 있습니다.

def test():
    print('function is called')
    return True

print(True and test())
# function is called
# True

print(False and test())
# False

print(True or test())
# True

print(False or test())
# function is called
# True
Copied title and URL