소개
본 랩 (lab) 에서는 효과적인 코드를 작성하는 데 필수적인 Python 의 다양한 연산자 (operator) 에 대해 포괄적으로 이해하게 됩니다. 산술, 비교, 할당, 논리, 비트, 멤버십, 그리고 식별 연산자를 탐색하고 실습할 것입니다.
통합된 VS Code 편집기와 터미널을 사용한 실습을 통해 계산 수행 방법, 값 비교 방법, 값 할당 방법, 조건 결합 방법, 비트 조작 방법, 멤버십 확인 방법, 그리고 객체 동일성 비교 방법을 배우게 됩니다. 이 랩이 끝날 때쯤이면 이러한 연산자들을 능숙하게 사용하여 더 복잡하고 기능적인 Python 프로그램을 구축할 수 있게 될 것입니다.
산술 및 비교 연산자 탐색
이 단계에서는 Python 의 기본적인 산술 (arithmetic) 연산자와 비교 (comparison) 연산자를 탐색합니다. 이 연산자들은 프로그램 내에서 계산을 수행하고 결정을 내리는 데 필수적입니다. 랩 환경에서는 이미 ~/project 디렉토리에 operators.py라는 파일이 생성되어 있습니다.
먼저, VS Code 편집기 왼쪽의 파일 탐색기에서 operators.py 파일을 찾아 엽니다. 모든 코드는 이 단일 파일에 작성할 것입니다.
산술 연산자부터 시작하겠습니다. 다음 Python 코드를 operators.py 파일에 추가하세요:
## Arithmetic Operators
a = 21
b = 5
print(f'{a} + {b} = {a + b}')
print(f'{a} - {b} = {a - b}')
print(f'{a} * {b} = {a * b}')
print(f'{a} / {b} = {a / b}') ## Standard division
print(f'{a} // {b} = {a // b}') ## Floor division, rounds down to the nearest whole number
print(f'{a} % {b} = {a % b}') ## Modulo, returns the remainder
print(f'{a} ** {b} = {a ** b}') ## Exponentiation, a to the power of b
코드를 추가한 후, Ctrl + S를 눌러 파일을 저장합니다.
스크립트를 실행하려면, 상단 메뉴에서 Terminal > New Terminal을 선택하여 VS Code 의 통합 터미널을 엽니다. 그런 다음 다음 명령어를 실행합니다:
python ~/project/operators.py
터미널에서 다음과 같은 출력을 보게 될 것입니다:
21 + 5 = 26
21 - 5 = 16
21 * 5 = 105
21 / 5 = 4.2
21 // 5 = 4
21 % 5 = 1
21 ** 5 = 4084101
다음으로, 비교 연산자를 탐색해 보겠습니다. 이 연산자들은 두 값을 비교하여 불리언 (Boolean) 값인 True 또는 False를 반환합니다.
operators.py 파일의 끝에 다음 코드를 추가하세요:
## Comparison Operators
print("\n--- Comparison Operators ---")
a = 6
b = 5
print(f'{a} == {b} is {a == b}') ## Equal to
print(f'{a} != {b} is {a != b}') ## Not equal to
print(f'{a} > {b} is {a > b}') ## Greater than
print(f'{a} < {b} is {a < b}') ## Less than
print(f'{a} >= {b} is {a >= b}') ## Greater than or equal to
print(f'{a} <= {b} is {a <= b}') ## Less than or equal to
파일을 다시 저장하고 터미널에서 실행합니다:
python ~/project/operators.py
출력에는 이제 비교 연산의 결과가 포함됩니다:
21 + 5 = 26
21 - 5 = 16
21 * 5 = 105
21 / 5 = 4.2
21 // 5 = 4
21 % 5 = 1
21 ** 5 = 4084101
--- Comparison Operators ---
6 == 5 is False
6 != 5 is True
6 > 5 is True
6 < 5 is False
6 >= 5 is True
6 <= 5 is False
이제 Python 스크립트에서 산술 연산자와 비교 연산자를 성공적으로 사용해 보았습니다.
할당 및 논리 연산자 연습
이 단계에서는 할당 연산자 (assignment operators) 와 논리 연산자 (logical operators) 사용을 실습합니다. 할당 연산자는 변수의 값을 할당하거나 업데이트하는 데 사용되며, 논리 연산자는 조건문을 결합하는 데 사용됩니다.
VS Code 편집기에서 계속해서 operators.py 파일을 작업합니다.
먼저, 할당 연산자의 예시를 추가해 보겠습니다. 이 연산자들은 연산을 수행하고 그 결과를 동일한 변수에 다시 할당하는 간결한 방법을 제공합니다.
operators.py 파일의 끝에 다음 코드를 추가하세요:
## Assignment Operators
print("\n--- Assignment Operators ---")
a = 10
b = 3
print(f'Initial a: {a}')
c = a
c += b ## Equivalent to c = c + b
print(f'a += b: {c}')
c = a
c -= b ## Equivalent to c = c - b
print(f'a -= b: {c}')
c = a
c *= b ## Equivalent to c = c * b
print(f'a *= b: {c}')
c = a
c /= b ## Equivalent to c = c / b
print(f'a /= b: {c}')
## Walrus operator (Python 3.8+)
## It assigns a value to a variable as part of a larger expression.
print("\n--- Walrus Operator ---")
text = 'hello python'
if (n := len(text)) > 10:
print(f'The string is long enough ({n} characters)')
파일을 저장하고 터미널에서 실행합니다:
python ~/project/operators.py
할당 연산자에 대한 출력을 보게 될 것입니다:
... (output from previous step) ...
--- Assignment Operators ---
Initial a: 10
a += b: 13
a -= b: 7
a *= b: 30
a /= b: 3.3333333333333335
--- Walrus Operator ---
The string is long enough (12 characters)
이제 논리 연산자 (and, or, not) 의 예시를 추가해 보겠습니다. 이 연산자들은 불리언 값과 함께 작동하지만, 다른 타입과도 작동할 수 있습니다. Python 에서는 0, None, 그리고 빈 컬렉션 ('', [], {}) 과 같은 값들은 False로 간주됩니다. 다른 모든 값은 True로 간주됩니다.
operators.py 파일의 끝에 다음 코드를 추가하세요:
## Logical Operators
print("\n--- Logical Operators ---")
x = True
y = False
print(f'{x} and {y} is {x and y}')
print(f'{x} or {y} is {x or y}')
print(f'not {x} is {not x}')
## Evaluation with non-boolean values
a = 10 ## True
b = 0 ## False
print(f'{a} and {b} returns {a and b}') ## Returns the first Falsey value or the last Truthy value
print(f'{a} or {b} returns {a or b}') ## Returns the first Truthy value or the last Falsey value
파일을 저장하고 다시 실행합니다:
python ~/project/operators.py
출력에는 이제 논리 연산의 결과가 포함됩니다:
... (output from previous examples) ...
--- Logical Operators ---
True and False is False
True or False is True
not True is False
10 and 0 returns 0
10 or 0 returns 10
이제 Python 에서 할당 연산자와 논리 연산자를 사용하는 것을 실습했습니다.
비트 연산자 학습
이 단계에서는 비트 연산자 (bitwise operators) 에 대해 학습합니다. 이 연산자들은 정수 (integers) 의 이진수 (binary, base-2) 표현에 직접 연산을 수행합니다. 이는 저수준 (low-level) 데이터 조작에 유용합니다.
계속해서 operators.py 파일을 편집합니다.
먼저, bin() 함수를 사용하여 몇 가지 숫자의 이진수 표현을 살펴보겠습니다. 0b 접두사는 뒤따르는 숫자가 이진수임을 나타냅니다.
operators.py 끝에 다음 코드를 추가하세요:
## Bitwise Operators
print("\n--- Bitwise Operators ---")
a = 5 ## Binary: 0b101
b = 9 ## Binary: 0b1001
print(f'Binary of {a} is {bin(a)}')
print(f'Binary of {b} is {bin(b)}')
## For clarity, let's align them with 4 bits:
## a = 0101
## b = 1001
## Bitwise AND (&): Sets each bit to 1 if both bits are 1.
## 0101 & 1001 = 0001 (Decimal 1)
print(f'{a} & {b} = {a & b}')
## Bitwise OR (|): Sets each bit to 1 if one of the two bits is 1.
## 0101 | 1001 = 1101 (Decimal 13)
print(f'{a} | {b} = {a | b}')
## Bitwise XOR (^): Sets each bit to 1 if only one of the two bits is 1.
## 0101 ^ 1001 = 1100 (Decimal 12)
print(f'{a} ^ {b} = {a ^ b}')
## Bitwise NOT (~): Inverts all the bits.
## ~a is equivalent to -(a+1)
print(f'~{a} = {~a}')
## Left Shift (<<): Shifts bits to the left, filling with zeros.
## Equivalent to multiplying by 2**n.
## 5 << 2 means 0101 becomes 10100 (Decimal 20)
print(f'{a} << 2 = {a << 2}')
## Right Shift (>>): Shifts bits to the right, discarding bits from the right.
## Equivalent to floor division by 2**n.
## 9 >> 2 means 1001 becomes 10 (Decimal 2)
print(f'{b} >> 2 = {b >> 2}')
파일을 저장하고 터미널에서 스크립트를 실행합니다:
python ~/project/operators.py
각 비트 연산이 시연된 출력을 보게 될 것입니다:
... (output from previous steps) ...
--- Bitwise Operators ---
Binary of 5 is 0b101
Binary of 9 is 0b1001
5 & 9 = 1
5 | 9 = 13
5 ^ 9 = 12
~5 = -6
5 << 2 = 20
9 >> 2 = 2
이제 비트 수준에서 정수를 조작하기 위해 비트 연산자를 사용하는 방법을 배웠습니다.
멤버십 및 동일성 연산자 사용
마지막 단계에서는 멤버십 연산자 (in, not in) 와 동일성 연산자 (is, is not) 에 대해 알아봅니다. 멤버십 연산자는 값이 시퀀스 내에 존재하는지 테스트하는 반면, 동일성 연산자는 두 변수가 메모리에서 정확히 동일한 객체를 참조하는지 확인합니다.
계속해서 operators.py 파일을 작업합니다.
먼저, 멤버십 연산자의 예시를 추가해 보겠습니다. 이 연산자들은 리스트 (lists), 튜플 (tuples), 문자열 (strings) 과 같은 시퀀스에서 흔히 사용됩니다.
operators.py 파일의 끝에 다음 코드를 추가하세요:
## Membership Operators
print("\n--- Membership Operators ---")
my_list = [1, 3, 5, 7]
print(f'3 in {my_list} is {3 in my_list}')
print(f'4 not in {my_list} is {4 not in my_list}')
greeting = "hello world"
print(f'"world" in "{greeting}" is {"world" in greeting}')
파일을 저장하고 실행합니다:
python ~/project/operators.py
멤버십 연산자에 대한 출력은 다음과 같습니다:
... (output from previous steps) ...
--- Membership Operators ---
3 in [1, 3, 5, 7] is True
4 not in [1, 3, 5, 7] is True
"world" in "hello world" is True
이제 동일성 연산자를 살펴보겠습니다. is(동일성) 와 ==(동등성) 의 차이점을 이해하는 것이 중요합니다. ==는 두 객체의 값이 같은지 확인하는 반면, is는 두 객체가 동일한 객체인지 (즉, 메모리 주소가 같은지) 확인합니다.
operators.py 파일에 다음 코드를 추가하세요:
## Identity Operators
print("\n--- Identity Operators ---")
## For small integers, Python often reuses the same object.
x = 256
y = 256
print(f'x is y (for 256): {x is y}') ## This is often True
## For larger integers, Python may create separate objects.
a = 257
b = 257
print(f'a is b (for 257): {a is b}') ## This is often False
## For mutable objects like lists, they are different objects even if their content is the same.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(f'list1 == list2: {list1 == list2}') ## Checks for equal content (True)
print(f'list1 is list2: {list1 is list2}') ## Checks for same object (False)
print(f'list1 is not list2: {list1 is not list2}') ## Checks for different objects (True)
파일을 저장하고 마지막으로 한 번 더 실행합니다:
python ~/project/operators.py
출력은 동등성 (equality) 과 동일성 (identity) 의 차이점을 보여줍니다:
... (output from previous examples) ...
--- Identity Operators ---
x is y (for 256): True
a is b (for 257): True
list1 == list2: True
list1 is list2: False
list1 is not list2: True
멤버십 연산자와 동일성 연산자를 성공적으로 사용했으며, Python 의 주요 연산자 유형에 대한 탐색을 완료했습니다.
요약
본 실습 (lab) 을 통해 Python 의 다양한 유형의 연산자 (operators) 에 대한 실습 경험을 쌓았습니다. 계산을 수행하고 조건을 평가하기 위해 기본적인 산술 (arithmetic) 및 비교 (comparison) 연산자를 탐색하는 것으로 시작했습니다. 그런 다음 효율적인 변수 업데이트를 위한 할당 연산자 (assignment operators) 와 조건부 논리 (conditional logic) 를 결합하기 위한 논리 연산자 (logical operators) 사용을 연습했습니다.
더 나아가, 저수준 데이터 조작을 이해하기 위해 비트 연산자 (bitwise operators) 를 깊이 파고들었고, 항목 존재 여부와 객체 동일성을 확인하기 위해 멤버십 연산자 (membership operators) 와 동일성 연산자 (identity operators) 로 마무리했습니다. VS Code 편집기에서 각 연산자 유형에 대한 코드를 작성하고 실행함으로써, 향후 Python 프로그래밍에서 이러한 필수 도구를 사용하는 데 있어 견고한 기반을 다졌습니다.



