Python

Chapter 01. 파이썬 자료형

초코너무조코 2025. 4. 7. 11:10
728x90

파이썬에서 자료형은 데이터의 종류를 정의하는 가장 기본적인 개념입니다. 숫자, 문자, 리스트, 딕셔너리 등 다양한 형태의 데이터를 다루기 위해 꼭 알아야 할 주제죠. 이 글에서는 파이썬의 기본 자료형을 예제와 함께 상세히 설명합니다.


1. 숫자형(Number)

파이썬에서 숫자형은 int(정수)와 float(실수)를 기본으로 합니다.

🔹 정수형 (int)

a = 10
b = -5
print(type(a))  # <class 'int'>

특징

  • 소수점 없음
  • 크기 제한 없음 (메모리 허용 범위 내)

🔹 실수형 (float)

pi = 3.14159
print(type(pi))  # <class 'float'>

연산 예시

x = 10
y = 3
print(x / y)  # 3.333...
print(x // y) # 3 (정수 나눗셈)
print(x % y)  # 1 (나머지)

🔹 형변환

a = 10
print(float(a))  # 10.0

b = 3.99
print(int(b))  # 3 (소수점 이하 버림)

2. 문자열(String)

문자열은 '텍스트' 또는 "텍스트" 형태로 표현됩니다.

text = "Hello, Python!"
print(text.upper())  # 대문자
print(text.lower())  # 소문자

슬라이싱 & 인덱싱

s = "Python"
print(s[0])    # P
print(s[-1])   # n
print(s[1:4])  # yth

문자열 연산

print("Py" + "thon")     # Python
print("Hi! " * 3)        # Hi! Hi! Hi!

3. 리스트(List)

리스트는 순서가 있는 데이터 집합입니다. 대괄호 []를 사용합니다.

fruits = ["사과", "바나나", "포도"]
print(fruits[0])     # 사과
print(fruits[-1])    # 포도

리스트 메서드

fruits.append("수박")  # 맨 뒤에 추가
fruits.remove("바나나")
print(len(fruits))    # 길이

4. 튜플(Tuple)

리스트와 유사하지만 값을 변경할 수 없음(불변)

t = (1, 2, 3)
print(t[1])  # 2

튜플은 데이터 보호가 필요한 상황에서 유용합니다.


5. 딕셔너리(Dictionary)

키:값 쌍으로 구성된 자료형, {} 사용

person = {"name": "Alice", "age": 25}

# 값 추가
person["city"] = "New York"
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'New York'}

# 값 수정
person["age"] = 33
print(person)  # {'name': 'Alice', 'age': 33, 'city': 'New York'}

# 특정 키 삭제
del person["city"]
print(person)  # {'name': 'Alice', 'age': 25}

# 모든 키-값 삭제
person.clear()
print(person)  # {}

딕셔너리 접근 방법

# openai API response 예시
data = {
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1677858242,
  "model": "gpt-4-1106-preview",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "안녕하세요! 무엇을 도와드릴까요?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 10,
    "total_tokens": 20
  }
}

# Q. content에 들어있는 메세지 내용을 추출해주세요.
data['choices'][0]['message']['content']

 

딕셔너리의 주요 메서드

person = {"name": "Alice", "age": 25, "city": "New York"}

print(person.keys())   # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 25, 'New York'])
print(person.items())  # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

 

 


6. 집합(Set)

중복 제거에 유용한 자료형, {} 또는 set() 사용

s = set([1, 2, 2, 3, 4])
print(s)  # {1, 2, 3, 4}

집합 연산

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)  # 합집합
print(a & b)  # 교집합
print(a - b)  # 차집합

7. 불(Boolean)

참(True), 거짓(False) 값을 표현하는 자료형

a = True
b = False

print(a and b)  # False
print(a or b)   # True
print(not a)    # False

✅ 정리

자료형 특징

int / float 숫자형
str 문자열
list 순서 있는 변경 가능한 자료
tuple 순서 있지만 변경 불가
dict 키-값 구조
set 중복 없는 집합
bool True / False

 

728x90