에듀테크 프로젝트 대시보드
함수 기초
def 로 정의하고, 함수도 값처럼 변수에 담고 인자로 넘길 수 있는 일급 객체입니다.
def greet(name):
"""인사말을 반환한다.""" # docstring
return f"안녕, {name}!"
msg = greet("민수")
def log(message):
print(message)
# return 이 없으면 None 반환
x = log("hi") # x == Nonedef connect(host, port=8080, timeout=30):
...
connect("localhost") # 위치 인자
connect("localhost", 9000)
connect("localhost", timeout=60) # 키워드 인자 (순서 무관)
# 기본값은 정의 시 "한 번만" 평가됨
def f(x, cache={}): # 위험 — 모든 호출이 같은 dict 공유
...
def f(x, cache=None): # 올바른 패턴
if cache is None:
cache = {}def stats(nums):
return min(nums), max(nums), sum(nums) / len(nums)
lo, hi, avg = stats([1, 2, 3, 4]) # 튜플 언패킹
# 일부만 필요하면
lo, *_ = stats(nums)def double(x): return x * 2
f = double # 변수에 할당
f(21) # => 42
funcs = [str.upper, str.strip, str.title]
for fn in funcs:
text = fn(text)
def apply(fn, value): # 인자로 전달
return fn(value)def area(width: float, height: float) -> float:
"""직사각형 넓이.
Args:
width: 가로 길이
height: 세로 길이
Returns:
넓이 (width * height)
"""
return width * height
area.__doc__ # docstring 접근
help(area) # 문서 출력def todo():
pass # 빈 함수 (문법상 필요)
def stub() -> int:
... # Ellipsis — "나중에 구현" 관례
def noop():
"""의도적으로 아무것도 안 함."""
return