반응형
📘 Day 16. 함수 고급 활용과 모듈의 기초
1. 함수 인수 고급 정리
✅ Keyword 가변 인수 (**kwargs)
- 함수 정의 시 **kwargs를 사용하면 개수에 상관없이 키워드 인수를 받을 수 있음
- 전달된 값은 딕셔너리 형태로 저장됨
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key} : {value}")
print_info(name="지훈", age=18, score=95)
✅ 함수 호출 시 unpacking
자료형 기호 설명
tuple | * | 인수 여러 개로 분리 |
dict | ** | 키워드 인수로 분리 |
def introduce(name, age):
print(f"{name}은 {age}살입니다.")
info = ("지수", 20)
introduce(*info)
data = {"name": "민수", "age": 19}
introduce(**data)
2. 모듈(Module)
✅ 모듈이란?
- 변수, 함수, 클래스를 모아놓은 .py 파일
- 다른 파이썬 스크립트에서 불러와서 재사용 가능
✅ 모듈의 종류
유형 설명
기본 모듈 | 파이썬에 기본 탑재되어 있는 표준 라이브러리 |
3rd party 모듈 | 별도로 설치가 필요한 외부 패키지 (예: numpy, pandas) |
사용자 정의 모듈 | 직접 작성한 .py 파일을 모듈로 사용 가능 |
✅ 모듈 불러오는 방법
# 전체 모듈 불러오기
import math
print(math.sqrt(16)) # 4.0
# 별명 사용
import math as m
print(m.pi)
# 특정 함수만 불러오기
from math import sqrt
print(sqrt(25))
3. 사용자 정의 모듈 만들기
- score_module.py라는 파일을 만들어 함수들을 모아두면 다른 파일에서 쉽게 불러와 사용 가능
예:
# score_module.py
def input_score():
...
def calculate_score():
...
def print_score():
...
사용:
from score_module import input_score, calculate_score, print_score
students = input_score()
calculate_score(students)
print_score(students)
4. 실습 문제: 함수로 나눠 작성하기
💡 문제:
5명 학생의 이름과 점수 2개를 입력 받아 총점과 평균을 구해 출력하시오.
🔧 함수 구성
✅ input_score()
- 이름과 두 과목 점수를 입력받아 딕셔너리에 저장
- 총 5명 입력
- 점수는 0~100 사이만 허용
def input_score():
students = {}
for _ in range(5):
name = input("이름 입력: ")
score1 = int(input("점수1 입력: "))
score2 = int(input("점수2 입력: "))
if 0 <= score1 <= 100 and 0 <= score2 <= 100:
students[name] = [score1, score2]
else:
print("점수는 0~100 사이여야 합니다.")
return students
✅ calculate_score(data)
- 총점과 평균을 구해 딕셔너리에 추가
def calculate_score(data):
for name, scores in data.items():
total = sum(scores)
avg = total / len(scores)
data[name] = scores + [total, avg]
✅ print_score(data)
- 이름, 점수1, 점수2, 총점, 평균 출력
def print_score(data):
print("이름 점수1 점수2 총점 평균")
for name, scores in data.items():
print(f"{name:4} {scores[0]:6} {scores[1]:6} {scores[2]:4} {scores[3]:.2f}")
✅ 실행 흐름
students = input_score()
calculate_score(students)
print_score(students)
✅ 오늘의 정리
내용 요약
함수 인수 확장 | *args, **kwargs, unpacking |
모듈의 개념 | .py 파일에 함수/변수를 모아 재사용 |
모듈 사용 방법 | import, from import, as 별칭 사용 |
실습 예제 | 입력 → 계산 → 출력의 함수 분리 구조 연습 |
다음 차시에는 예외 처리와 파일 처리를 통해
보다 견고한 프로그램을 만드는 방법을 배웁니다.
'십대를 위한 코딩 > 십대를 위한 파이썬' 카테고리의 다른 글
15. 함수 인자 활용과 모듈 개념 이해 (0) | 2025.04.05 |
---|---|
14. 함수(Function)의 정의, 구조, 그리고 호출 방식 (1) | 2025.04.04 |
13. 집합(Set)과 함수(Function)의 기초 (1) | 2025.04.03 |
12. 딕셔너리 메서드와 실전 활용 (0) | 2025.04.02 |
11. 딕셔너리(dict)의 개념과 활용 (1) | 2025.04.01 |