본문 바로가기

Python

Boolean, 비교연산자 / 논리연산자

728x90
반응형

참(True) , 거짓(False) 을 나타내는 Boolean

비교연산자 : 두 값의 관계를 판단 
논리연산자 : 두 값읜 논릿값을 판단

if , while 구문을 작성할 때 비교 / 논리 연산자를 자주 사용

 

비교연산자

비교 결과가 맞으면 True 틀리면 False

ex)
>>> 10 == 10
True

>>> 10 != 5
True

< 주의 >
>>> 'Python' == 'python' 
False

여기서 대소문자가 차이도 다른 문자열로 판단

is / is not

is, 와 is not 은 객체(object) 를 비교

1(정수) 와 1.0(실수) 는 차이점이 있지만 값은 동일

따라서 '==' 로 비교해보면 True
>>> 1 == 1.0
True

정수 객체와 실수 객체가 다르므로 " is 비교 연산자는 " False
>>> 1 is 1.0
False

is not 은 논릿값을 뒤집는다
>>> 1 is not 1.0
True

 

논리연산자

not , and , or 순서로 존재

1. not 

>>> not True
False

>>> not False
True 

처럼 not은 논릿값을 뒤집는다

 

2. and

A and B

A B A and B
True True True
True False False
False True False
False False False

>>> True and True
True 

>>> True and False
False

>>> False and True
False

>>> False and False
Fasle 

3. or

A or B

A B A or B
True True True
True False True
False True True
False False True

>>> True or True
True 

>>> True or False
True

>>> False or True
True

>>> False or False
Fasle 

 

not , and , or 순으로 판단한다

ex) 

>>> not True and False or not False
True 

풀이)

>>> not True and False or not False
False and False or True
False or True
True

Tip)

>>> ((not True) and False) or (not False)
True

괄호를 이용하여 판단순서를 명확히 표시하면 해석에 용이함

비교연산자 ( is, is not , == , != , <, >, <=, >= ) 를 먼저 판단하고
논리연산자 ( not , and , or ) 을 판단하게 된다

논리연산에서 가장 중요한 부분이 단락평가(short-circuit evalution) 이다

첫 번째 값만으로 결과가 확실할 때 두 번째 값은 확인(평가) 하지 않는 방법 

즉, and 연산자는 두 값이 모두 참이여야 참이므로 첫번째 값이 거짓이면 두번째 값을 검증하지 않고 바로 False 처리 해버린다

728x90
반응형

'Python' 카테고리의 다른 글

딕셔너리 { Dictionary, dict }  (0) 2020.06.15
자료형  (0) 2020.06.15
리스트 [ List ]  (0) 2020.06.15
str() , int()  (0) 2020.06.12
문자열  (0) 2020.06.11