연산자(Operators)

연산자는 프로그래밍의 기본적인 구성 요소로, 데이터를 조작하고 계산하는 데 사용된다.

산술 연산자

산술 연산자는 수학적 계산을 수행한다.

연산자의미예시결과
+덧셈5 + 38
-뺄셈5 - 32
*곱셈5 * 315
/나눗셈5 / 31.6666…
//5 // 31
%나머지5 % 32
**거듭제곱5 ** 3125

비교 연산자

비교 연산자는 값을 비교하고 불리언 결과를 반환한다.

연산자의미예시결과
==같음5 == 3False
!=다름5!= 3True
>5 > 3True
<작음5 < 3False
>=크거나 같음5 >= 3True
<=작거나 같음5 <= 3False

논리 연산자

논리 연산자는 조건문을 결합한다.

연산자의미예시결과
and논리곱True and FalseFalse
or논리합True or FalseTrue
not논리부정not TrueFalse

할당 연산자

할당 연산자는 변수에 값을 할당한다.

연산자의미예시동일 표현
=할당x = 5x = 5
+=더하기 할당x += 3x = x + 3
-=빼기 할당x -= 3x = x - 3
*=곱하기 할당x *= 3x = x * 3
/=나누기 할당x /= 3x = x / 3
//=몫 할당x //= 3x = x // 3
%=나머지 할당x %= 3x = x % 3
**=거듭제곱 할당x **= 3x = x ** 3

비트 연산자

비트 연산자는 이진수 레벨에서 연산을 수행한다.

연산자의미예시결과
&비트 AND5 & 31
|비트 OR5 | 37
^비트 XOR5 ^ 36
~비트 NOT~5-6
«좌측 시프트5 « 110
»우측 시프트5 » 12

비트 AND (&)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 두 비트가 모두 1일 때만 1, 아니면 0
"""
    0101 (5)
  & 0011 (3)
    ----
    0001 (1)
"""
a = 5  # 0101
b = 3  # 0011
result = a & b  # 0001 (1)
print(f"5 & 3 = {result}")

비트 OR (|)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 두 비트 중 하나라도 1이면 1
"""
    0101 (5)
  | 0011 (3)
    ----
    0111 (7)
"""
a = 5  # 0101
b = 3  # 0011
result = a | b  # 0111 (7)
print(f"5 | 3 = {result}")

비트 XOR (^)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 두 비트가 다를 때만 1
"""
    0101 (5)
  ^ 0011 (3)
    ----
    0110 (6)
"""
a = 5  # 0101
b = 3  # 0011
result = a ^ b  # 0110 (6)
print(f"5 ^ 3 = {result}")

비트 NOT (~)

1
2
3
4
5
6
7
8
# 모든 비트 반전 (0→1, 1→0)
# 2의 보수: -(x+1)
"""
~5 = -6 (비트 반전 후 2의 보수)
"""
a = 5
result = ~a  # -6
print(f"~5 = {result}")

좌측 시프트 («)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 비트를 왼쪽으로 이동 (2를 곱하는 효과)
"""
5 << 1:
0101 -> 1010 (10)
5 << 2:
0101 -> 10100 (20)
"""
a = 5
result1 = a << 1  # 10
result2 = a << 2  # 20
print(f"5 << 1 = {result1}")
print(f"5 << 2 = {result2}")

우측 시프트 (»)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 비트를 오른쪽으로 이동 (2로 나누는 효과)
"""
5 >> 1:
0101 -> 0010 (2)
5 >> 2:
0101 -> 0001 (1)
"""
a = 5
result1 = a >> 1  # 2
result2 = a >> 2  # 1
print(f"5 >> 1 = {result1}")
print(f"5 >> 2 = {result2}")

실제 사용 예시

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 1. 비트 마스킹
def check_bit(number, position):
    """특정 위치의 비트가 1인지 확인"""
    return (number & (1 << position)) != 0

# 2. 비트 설정
def set_bit(number, position):
    """특정 위치의 비트를 1로 설정"""
    return number | (1 << position)

# 3. 비트 클리어
def clear_bit(number, position):
    """특정 위치의 비트를 0으로 설정"""
    return number & ~(1 << position)

# 4. 비트 토글
def toggle_bit(number, position):
    """특정 위치의 비트를 반전"""
    return number ^ (1 << position)

# 사용 예시
number = 5  # 0101
print(f"Original number: {bin(number)}")

# 비트 확인
pos = 2
is_set = check_bit(number, pos)
print(f"Bit at position {pos} is set: {is_set}")

# 비트 설정
number = set_bit(number, 3)
print(f"After setting bit 3: {bin(number)}")

# 비트 클리어
number = clear_bit(number, 2)
print(f"After clearing bit 2: {bin(number)}")

# 비트 토글
number = toggle_bit(number, 1)
print(f"After toggling bit 1: {bin(number)}")

실용적인 예시

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 1. 짝수/홀수 확인
def is_even(n):
    return (n & 1) == 0

# 2. 2의 거듭제곱 확인
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0

# 3. 두 수 교환
def swap_numbers(a, b):
    a = a ^ b
    b = a ^ b
    a = a ^ b
    return a, b

# 4. 비트 수 세기
def count_bits(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

# 사용 예시
print(f"Is 4 even? {is_even(4)}")
print(f"Is 8 power of 2? {is_power_of_two(8)}")
a, b = 5, 10
a, b = swap_numbers(a, b)
print(f"After swap: a={a}, b={b}")
print(f"Number of 1 bits in 7: {count_bits(7)}")

비트 연산자들이 사용되는 경우

  1. 플래그나 상태 관리
  2. 메모리 효율적인 데이터 저장
  3. 암호화/복호화
  4. 하드웨어 제어
  5. 성능 최적화

6. 멤버십 연산자

연산자의미예시결과
in포함 여부‘a’ in ‘abc’True
not in비포함 여부’d’ not in ‘abc’True

7. 식별 연산자

연산자의미예시결과
is동일 객체 여부x is yx와 y가 같은 객체면 True
is not비동일 객체 여부x is not yx와 y가 다른 객체면 True

연산자 우선순위

  1. (): 괄호
  2. **: 지수
  3. +x, -x, ~x: 단항 연산자
  4. *, /, //, %: 곱셈, 나눗셈
  5. +, -: 덧셈, 뺄셈
  6. «, »: 시프트
  7. &: 비트 AND
  8. ^: 비트 XOR
  9. |: 비트 OR
  10. ==,!=, >, <, >=, <=: 비교
  11. and, or, not: 논리
  12. =: 할당

참고 및 출처