[Python] 기초 - 연산자

ITmakesmeSoft·2022년 9월 3일
0

PYTHON [BASIC]

목록 보기
3/13
post-thumbnail

연산자

  1. 산술 연산자
  2. 비교 연산자
  3. 논리 연산자
  4. 복합 연산자
  5. 식별 연산자
  6. 멤버십 연산자

1. 산술 연산자

2. 비교 연산자

: 수학에서 등호, 부등호와 동일한 개념. 주로 조건문에 사용되며, 값을 비교할 때 사용함.
결과는 True/False로 리턴함

print(3>6)        # False
print(3.0==3)     # True
print(3>=0)       # True
print('3'!=3)     # True
print('Hi'=='Hi') # False

3. 논리 연산자

  • 여러 가지 조건이 있을 때
    • 모든 조건을 만족하거나(and), 여러 조건 중 하나만 만족해도 될 때(or), 특정 코드를 실행하고 싶을 때 사용.

    • 일반적으로 비교 연산자와 함께 사용

      | 연산자 | 내용 |
      | --- | --- |
      | A and B | A와 B 모두 True시 True |
      | A or B | A와 B 모두 False시 False |
      | Not | True를 False로
      False를 True로 |
      print(True and True) # True
      print(True and False) # False
      print(False and True) # False 
      print(False and False) # False
      
      print(True or True) # True
      print(True or False) # True
      print(False or True) # True
      print(False or False) # False
  • 주의할 점
    • Falsy : False는 아니지만 False로 취급되는 다양한 값
      • 0, 0.0, (), [], {}, None, “”(빈문자열)
    • 논리 연산자도 우선순위가 존재
      • not, and, or 순으로 우선순위가 높음 ⇒ 소괄호로 묶으면 우선
  • 논리 연산자의 단축 평가
    # and연산에서 첫번째 값이 False인 경우 무조건 False ⇒ 첫번째 값 반환
    print(3 and 5) # 5
    print(3 and 0) # 0
    print(0 and 3) # 0
    print(0 and 0) # 0
    # 0은 False, 1은 True
    
    # 결과가 확실한 경우 두번째 값은 확인하지 않고 첫번째 값 반환
    print(5 or 3) # 5
    print(3 or 0) # 3
    print(0 or 3) # 3
    print(0 or 0) # 0
    
    # or연산에서 첫번째 값이 True인 경우 무조건 True ⇒ 첫번째 값 반환
    a = 5 and 4
    print(a)      # 4
    b = 5 or 3
    print(b)      # 5
    c = 0 and 5
    print(c)      # 0
    d = 5 or 0
    print(d)      # 5

4. 복합 연산자

복합 연산자는 연산과 할당이 동시에 이루어짐.
주로 반복문에서 갯수를 카운트 할때 사용.

5. 식별 연산자(Identity Operator)

is 연산자를 통해 동일한 객체(Object)인지 확인할 수 있음.

# 파이썬에서는 -5 부터 256 까지의 id가 동일.
a=-5
b=-5
print(a is b) # True

# 257 이후의 정수는 같은 값을 대입하더라도 다른 id를 참조.
a = 257  
b = 257
print(a is b) # False

6. 멤버십 연산자(Membership Operator)

요소가 시퀸스에 속해있는지 확인 가능

  • in 연산자 : 시퀀스에 속해있을 경우 True
  • not in 연산자 : 시퀀스에 속해있지 않을 경우 True
# in 연산자
string='abcd'
if 'a' in string:   # True
    print('True')

# not in 연산자
arr=['a','b','c','d'] 
if 'e' not in arr:  # True
    print('True')
profile
💎 Daniel LEE | SSAFY 8th

0개의 댓글