Day 10: 모듈과 패키지
모듈 임포트
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
from random import randint, choice
print(randint(1, 100))
print(choice(["사과", "바나나", "체리"]))
유용한 표준 라이브러리
| 모듈 | 용도 | 예시 |
|---|---|---|
math | 수학 함수 | math.ceil(3.2) |
random | 난수 생성 | random.shuffle(lst) |
os | 운영체제 인터페이스 | os.getcwd() |
sys | 시스템 매개변수 | sys.argv |
collections | 특수 컨테이너 | Counter, defaultdict |
itertools | 반복자 도구 | product, permutations |
사용자 정의 모듈
utils.py 파일을 만들어 모듈로 사용할 수 있습니다.
# utils.py
def add(a, b):
return a + b
PI = 3.14159
# main.py
from utils import add, PI
print(add(3, 5)) # 8
name == “main”
# calculator.py
def multiply(a, b):
return a * b
if __name__ == "__main__":
# 직접 실행할 때만 동작
result = multiply(3, 4)
print(f"결과: {result}")
패키지 구조
mypackage/
├── __init__.py
├── math_utils.py
└── string_utils.py
from mypackage.math_utils import add
from mypackage import string_utils
오늘의 연습문제
collections.Counter를 사용해 문자열에서 가장 많이 나온 문자 3개를 출력하세요.itertools.combinations로 로또 번호 조합 5개를 생성하세요.- 계산기 함수들을 모듈로 분리하고 메인 파일에서 임포트하여 사용하세요.