Python 핵심 데이터 타입 분석

숫자형 (Number)

불리언 (bool)

불리언 타입은 TrueFalse 두 가지 값을 가집니다. 내부적으로는 정수 1과 0으로 표현되며, 조건 판단 및 논리 연산에 사용됩니다.

정수형 (int)

파이썬의 정수형은 임의 정밀도를 지원하며, 기본 십진법 외에도 다양한 진법 표기법을 제공합니다:

  • 이진수: 접두사 0b
  • 팔진수: 접두사 0o
  • 십육진수: 접두사 0x

진법 변환 예제

decimal_value = 15

binary_result = bin(decimal_value)    # 10진수 → 2진수
print(binary_result)  # 출력: 0b1111

octal_result = oct(decimal_value)     # 10진수 → 8진수
print(octal_result)   # 출력: 0o17

hex_result = hex(decimal_value)        # 10진수 → 16진수
print(hex_result)     # 출력: 0xf

기본 산술 연산

print(7 + 3)      # 덧셈 → 10
print(7 - 3)      # 뺄셈 → 4
print(7 * 3)      # 곱셈 → 21
print(7 / 3)      # 나눗셈 → 2.333...
print(7 // 3)     # 몫 → 2
print(7 % 3)      # 나머지 → 1
print(7 ** 3)     # 거듭제곱 → 343
print(divmod(17, 3))  # 몫과 나머지 → (5, 2)

실수형 (float)

실수는 부동소수점 방식으로 저장되며, 매우 크거나 작은 수는 지수 표기법(e-notation)으로 표현할 수 있습니다:

  • 일반 소수: 3.14159, -0.001
  • 지수 표기: 1.5e10, 2.7e-5

부동소수점 정밀도 문제

실수는 이진수로 변환 시 반복되는 무한소수가 발생해 근사치 오차가 생길 수 있습니다. 예를 들어 0.1은 정확히 표현되지 않습니다.

고정밀도 계산: decimal 모듈

from decimal import Decimal, getcontext

getcontext().prec = 50  # 소수점 이하 50자리 정밀도 설정

high_precision = Decimal('1') / Decimal('3')
print(high_precision)  
# 출력: 0.33333333333333333333333333333333333333333333333333

중요: 기존 float 값을 Decimal로 변환하면 이미 손실된 정밀도를 복구할 수 없습니다. 반드시 문자열로 입력해야 합니다.

문자열 (str)

기본 생성

message = "Hello Python"
multiline = """여러 줄
문자열"""
raw_string = r"이스케이프 \n 무시됨"

주요 메서드

text = "  Python Programming  "

print(text.strip())        # 공백 제거 → "Python Programming"
print(text.upper())        # 대문자 변환
print(text.lower())        # 소문자 변환
print(text.replace("P", "J"))  # 문자 치환

words = text.split()       # 공백 기준 분할 → ['Python', 'Programming']
joined = "-".join(words)   # 문자열 결합 → "Python-Programming"

print(text.find("Pro"))    # 위치 검색 → 9
print("Pro" in text)       # 포함 여부 → True

서식화 (formatting)

name = "Alice"
age = 30

# .format() 사용
template1 = "이름: {}, 나이: {}".format(name, age)

# f-string (권장)
template2 = f"이름: {name}, 나이: {age}"

# 딕셔너리 활용
data = {"name": "Bob", "age": 25}
template3 = "이름: {name}, 나이: {age}".format(**data)

리스트 (list)

가변 시퀀스 자료형으로, 다양한 데이터를 순서 있게 저장합니다.

items = ["apple", "banana", "cherry"]

items.append("date")           # 끝에 추가
items.insert(1, "blueberry")    # 특정 위치 삽입
items[0] = "avocado"             # 값 수정

items.remove("banana")           # 값으로 삭제
del items[1]                     # 인덱스로 삭제

sliced = items[1:3]              # 슬라이싱
reversed_items = items[::-1]     # 역순

튜플 (tuple)

불변 시퀀스 자료형으로, 성능 최적화 및 해시 가능성이 필요할 때 사용됩니다.

coordinates = (10, 20, 30)
colors = ("red", "green", "blue")

print(coordinates[1])          # 접근 → 20
count_red = colors.count("red") # 등장 횟수
index_green = colors.index("green")  # 인덱스 찾기

딕셔너리 (dict)

키-값 쌍으로 구성된 해시 맵 구조입니다.

person = {
    "name": "John",
    "age": 28,
    "city": "Seoul"
}

person["job"] = "developer"      # 항목 추가
person["age"] = 29               # 값 갱신
del person["city"]               # 삭제

# 안전한 접근
name = person.get("name", "Unknown")

# 반복 처리
for key, value in person.items():
    print(f"{key}: {value}")

# 중첩 구조
nested = {
    "user": {"id": 1, "role": "admin"},
    "tags": ["python", "web"]
}
print(nested["user"]["role"])    # → "admin"

세트 (set)

순서 없고 중복을 허용하지 않는 집합 자료형입니다.

primes = {2, 3, 5, 7, 11}
evens = {2, 4, 6, 8, 10}

primes.add(13)                   # 요소 추가
primes.discard(11)               # 요소 제거 (존재하지 않아도 에러 없음)

union = primes | evens           # 합집합
intersection = primes & evens    # 교집합 → {2}
difference = primes - evens      # 차집합 → {3, 5, 7, 13}

print(3 in primes)               # 포함 여부 확인 → True

태그: python data types int float String

7월 25일 06:08에 게시됨