소개
본 실습에서는 Python 의 숫자 유형 (number types) 과 연산에 대한 기본적인 이해를 얻게 됩니다. 정수 (integer), 불리언 (boolean), 부동 소수점 (floating-point), 복소수 (complex number) 유형의 특성, 불변성 (immutability), 그리고 유형 및 메모리 주소를 확인하는 방법을 탐구할 것입니다. 실습을 통해 다양한 숫자 유형 간의 변환 방법과 기본적인 산술 연산을 수행하는 방법을 학습하여 Python 의 수치 처리 능력에 대한 지식을 공고히 할 것입니다.
정수 및 불리언 유형 탐색
이 단계에서는 Python 의 정수 (int) 및 불리언 (bool) 데이터 유형을 탐색합니다. 정수는 10, -5, 또는 0과 같은 정수 (whole numbers) 입니다. 불리언은 True 또는 False라는 두 가지 값 중 하나를 나타내며, 정수의 하위 유형 (subtype) 입니다.
Python 에서 중요한 개념은 불변성 (immutability) 입니다. 숫자 유형은 불변적이므로, 일단 숫자 객체가 생성되면 그 값을 변경할 수 없습니다. 변수를 새로운 숫자로 다시 할당하면, 메모리에서 새로운 객체를 가리키게 됩니다. 우리는 객체의 고유한 메모리 주소를 반환하는 내장 함수 id()와 데이터 유형을 보여주는 type() 함수를 사용하여 이를 확인할 수 있습니다.
실습 환경에는 이미 파일이 생성되어 있습니다. 왼쪽에 있는 WebIDE 파일 탐색기에서 ~/project/number_types.py 파일을 여십시오. 다음 코드를 파일에 추가하십시오.
## Demonstrate immutability of integers
a = 5
print(f"Initial value of a: {a}")
print(f"Type of a: {type(a)}")
print(f"ID of a: {id(a)}")
## Reassign 'a' to a new value
a = 6
print(f"\nNew value of a: {a}")
print(f"New ID of a: {id(a)}")
## Demonstrate boolean type
print("\n--- Boolean Types ---")
is_true = True
is_false = False
print(f"Value of is_true: {is_true}, Type: {type(is_true)}")
print(f"Value of is_false: {is_false}, Type: {type(is_false)}")
## Booleans behave like integers (1 and 0) in arithmetic
print(f"\nTrue + 5: {True + 5}")
print(f"False * 3: {False * 3}")
코드를 추가한 후 파일을 저장합니다. 스크립트를 실행하려면 WebIDE 에서 통합 터미널을 열고 다음 명령을 실행하십시오.
python ~/project/number_types.py
다음과 유사한 출력을 보게 될 것입니다. 메모리 주소 (ID) 는 시스템마다 다를 수 있다는 점에 유의하십시오.
Initial value of a: 5
Type of a: <class 'int'>
ID of a: <memory_address_1>
New value of a: 6
New ID of a: <memory_address_2>
--- Boolean Types ---
Value of is_true: True, Type: <class 'bool'>
Value of is_false: False, Type: <class 'bool'>
True + 5: 6
False * 3: 0
출력은 a가 5에서 6으로 재할당될 때 ID 가 변경되었음을 보여주며, 이는 새로운 정수 객체가 생성되었음을 확인시켜 줍니다. 또한 계산 시 True는 1로, False는 0으로 취급된다는 것을 보여줍니다.
부동 소수점 숫자 다루기
이 단계에서는 소수점 (decimal point) 을 가진 실수를 나타내는 부동 소수점 숫자 (float) 를 다룹니다. 부동 소수점 숫자의 일반적인 문제는 이진 형식으로 저장되기 때문에 발생하는 제한된 정밀도입니다. 이로 인해 계산 시 때때로 약간의 부정확성이 발생할 수 있습니다.
이러한 동작을 살펴보겠습니다. ~/project/number_types.py 파일을 다시 열고 파일 끝에 다음 코드를 추가하십시오. 이 코드는 정밀도 문제를 시연하고 이를 처리하는 두 가지 방법, 즉 간단한 반올림을 위한 round() 함수와 고정밀도 연산을 위한 decimal 모듈을 소개합니다.
## Demonstrate floating-point numbers and precision
print("\n--- Floating-Point Numbers ---")
result = 1.1 + 2.2
print(f"1.1 + 2.2 = {result}")
## Using round() for approximation
print(f"round(result, 1) = {round(result, 1)}")
## Using the decimal module for accurate calculations
from decimal import Decimal
## Pass numbers as strings to Decimal to avoid initial float inaccuracy
d1 = Decimal('1.1')
d2 = Decimal('2.2')
decimal_result = d1 + d2
print(f"Decimal('1.1') + Decimal('2.2') = {decimal_result}")
파일을 저장하고 터미널에서 스크립트를 다시 실행하십시오.
python ~/project/number_types.py
이제 출력에 다음 섹션이 포함될 것입니다.
--- Floating-Point Numbers ---
1.1 + 2.2 = 3.3000000000000003
round(result, 1) = 3.3
Decimal('1.1') + Decimal('2.2') = 3.3
보시다시피, 표준 부동 소수점 덧셈 1.1 + 2.2의 결과는 정확히 3.3이 아닙니다. round()는 출력을 형식화하는 데 도움이 될 수 있지만, decimal 모듈은 정확한 십진수 표현으로 계산을 수행하여 정확한 결과를 얻을 수 있는 방법을 제공합니다.
복소수 소개
Python 은 많은 과학 및 공학 분야에서 필수적인 복소수 (complex numbers) 에 대한 내장 지원을 제공합니다. 복소수는 실수부와 허수부를 가지며, 허수 단위 (imaginary unit) 를 j로 사용하여 a + bj 형태로 작성됩니다.
이 표기법을 사용하거나 complex(real, imag) 생성자를 사용하여 복소수를 생성할 수 있습니다. 실수부와 허수부는 .real 및 .imag 속성을 사용하여 접근할 수 있습니다.
~/project/number_types.py 파일을 계속 편집하십시오. 복소수를 탐색하기 위해 다음 코드를 파일 끝에 추가하십시오.
## Demonstrate complex numbers
print("\n--- Complex Numbers ---")
c1 = 3 + 4j
print(f"Complex number c1: {c1}")
print(f"Type of c1: {type(c1)}")
print(f"Real part of c1: {c1.real}")
print(f"Imaginary part of c1: {c1.imag}")
## Creating a complex number with the constructor
c2 = complex(5, -2)
print(f"\nComplex number c2: {c2}")
print(f"Real part of c2: {c2.real}")
print(f"Imaginary part of c2: {c2.imag}")
파일을 저장하고 터미널에서 스크립트를 다시 실행하십시오.
python ~/project/number_types.py
새로운 출력은 다음과 같습니다.
--- Complex Numbers ---
Complex number c1: (3+4j)
Type of c1: <class 'complex'>
Real part of c1: 3.0
Imaginary part of c1: 4.0
Complex number c2: (5-2j)
Real part of c2: 5.0
Imaginary part of c2: -2.0
정수로 정의하더라도 실수부와 허수부 모두 부동 소수점 숫자로 저장된다는 점에 유의하십시오.
숫자 유형 간 변환
Python 은 int(), float(), complex()와 같이 서로 다른 숫자 유형 간에 변환할 수 있는 내장 함수를 제공합니다. 이는 타입 캐스팅 (type casting) 이라고 합니다.
int(x):x를 정수 (integer) 로 변환합니다. 부동 소수점 숫자를 변환할 때는 반올림하는 것이 아니라 소수점 부분을 절삭합니다(잘라냅니다).float(x):x를 부동 소수점 숫자로 변환합니다.complex(real, imag): 복소수를 생성합니다.
유형 변환을 연습해 봅시다. ~/project/number_types.py 스크립트 끝에 다음 코드를 추가하십시오.
## Demonstrate type conversion
print("\n--- Type Conversion ---")
## Convert float to int (truncation)
float_num = 9.9
int_num = int(float_num)
print(f"float_num = {float_num}")
print(f"int(float_num) = {int_num}")
## Convert int to float
int_val = 10
float_val = float(int_val)
print(f"\nint_val = {int_val}")
print(f"float(int_val) = {float_val}")
## Convert string to number
str_num = "123.45"
converted_float = float(str_num)
converted_int = int(float(str_num)) ## Must convert to float first
print(f"\nstr_num = '{str_num}'")
print(f"float(str_num) = {converted_float}")
print(f"int(float(str_num)) = {converted_int}")
파일을 저장하고 스크립트를 다시 한 번 실행하십시오.
python ~/project/number_types.py
출력에 이제 이 섹션이 포함될 것입니다.
--- Type Conversion ---
float_num = 9.9
int(float_num) = 9
int_val = 10
float(int_val) = 10.0
str_num = '123.45'
float(str_num) = 123.45
int(float(str_num)) = 123
이 출력은 int()가 9.9의 소수점을 어떻게 9로 절삭하는지 명확하게 보여줍니다. 또한 소수점을 포함하는 문자열을 정수로 변환하는 데 필요한 두 단계 프로세스도 보여줍니다.
기본 산술 연산 수행
Python 은 모든 표준 산술 연산을 지원합니다. 서로 다른 숫자 유형 (예: int와 float) 의 피연산자로 연산을 수행하면, Python 은 자동으로 결과를 더 일반적인 유형으로 "확장 (widens)"합니다. 계층 구조는 int -> float -> complex입니다.
일반적인 연산자는 다음과 같습니다.
+(덧셈)-(뺄셈)*(곱셈)/(나눗셈 - 항상 float 결과를 반환)//(몫 연산/Floor Division - 나누고 가장 가까운 정수로 내림)%(나머지 연산/Modulo - 나눗셈의 나머지를 반환)**(거듭제곱)
탐색을 마무리하기 위해, 이러한 연산을 연습하기 위해 ~/project/number_types.py에 마지막 섹션을 추가해 보겠습니다.
## Demonstrate basic arithmetic operations
print("\n--- Basic Arithmetic Operations ---")
a = 10
b = 3
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")
print(f"{a} // {b} = {a // b}")
print(f"{a} % {b} = {a % b}")
print(f"{a} ** {b} = {a ** b}")
## Demonstrate mixed-type operations
print("\n--- Mixed-Type Operations ---")
int_op = 5
float_op = 2.5
result_mixed = int_op * float_op
print(f"{int_op} (int) * {float_op} (float) = {result_mixed} ({type(result_mixed)})")
파일을 저장하고 전체 스크립트를 다시 실행하십시오.
python ~/project/number_types.py
최종 출력에는 다음 내용이 포함됩니다.
--- Basic Arithmetic Operations ---
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 // 3 = 3
10 % 3 = 1
10 ** 3 = 1000
--- Mixed-Type Operations ---
5 (int) * 2.5 (float) = 12.5 (<class 'float'>)
이 출력은 각 연산자의 동작을 확인시켜 줍니다. 일반 나눗셈 /은 float 을 생성하는 반면, 몫 연산 //은 정수를 생성한다는 점에 유의하십시오. 정수와 float 간의 혼합 유형 연산은 예상대로 float 결과를 반환합니다.
요약
본 실습 (lab) 을 통해 Python 의 숫자 데이터 유형에 대한 견고한 기초를 다졌습니다. 정수 (integers), 부울 (booleans), 부동 소수점 숫자 (floats), 복소수 (complex numbers) 에 대해 배웠습니다. 또한 불변성 (immutability) 개념을 탐구하고 id() 및 type() 함수를 사용하여 객체를 검사했습니다. decimal 모듈을 사용하여 부동 소수점 정밀도 문제를 처리하고, int(), float(), complex()를 사용하여 다른 숫자 유형 간에 변환하며, 다양한 산술 연산을 수행하는 연습을 했습니다. 이 지식은 Python 에서 향후 프로그래밍 또는 데이터 분석 작업을 수행하는 데 매우 중요합니다.



