Python 함수

함수 정의

# 기본 함수
def greet():
    print("Hello")

# 매개변수와 반환값
def add(a, b):
    return a + b

# 여러 값 반환 (튜플)
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)

min_val, max_val, total = get_stats([1, 2, 3, 4, 5])

매개변수

# 기본값 매개변수
def greet(name, msg="Hello"):
    return f"{msg}, {name}"

greet("Alice")           # "Hello, Alice"
greet("Bob", "Hi")       # "Hi, Bob"

# 키워드 인자
def info(name, age, city):
    return f"{name}, {age}, {city}"

info(age=25, name="Alice", city="Seoul")

# *args: 가변 위치 인자 (튜플로 받음)
def sum_all(*args):
    return sum(args)

sum_all(1, 2, 3, 4, 5)   # 15

# **kwargs: 가변 키워드 인자 (딕셔너리로 받음)
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25)

# 모든 매개변수 조합
def func(a, b, *args, **kwargs):
    pass

람다 함수

# 기본 문법
lambda 매개변수: 표현식

# 예시
square = lambda x: x ** 2
add = lambda a, b: a + b

square(5)       # 25
add(3, 4)       # 7

# 정렬에서 활용
users = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
sorted(users, key=lambda x: x[1])   # 나이순 정렬

# map, filter와 함께
list(map(lambda x: x * 2, [1, 2, 3]))      # [2, 4, 6]
list(filter(lambda x: x > 2, [1, 2, 3, 4])) # [3, 4]

자주 쓰는 내장 함수

# 수학/통계
len([1, 2, 3])              # 3 (길이)
sum([1, 2, 3])              # 6 (합계)
min([1, 2, 3])              # 1 (최솟값)
max([1, 2, 3])              # 3 (최댓값)
abs(-5)                     # 5 (절댓값)
round(3.7)                  # 4 (반올림)
pow(2, 3)                   # 8 (거듭제곱)

# 타입 변환
int("42")                   # 42
float("3.14")               # 3.14
str(42)                     # "42"
list("abc")                 # ['a', 'b', 'c']
tuple([1, 2, 3])            # (1, 2, 3)
set([1, 1, 2])              # {1, 2}
dict([("a", 1), ("b", 2)])  # {'a': 1, 'b': 2}

# 반복 관련
range(5)                    # 0, 1, 2, 3, 4
enumerate(list)             # (인덱스, 값) 쌍
zip(list1, list2)           # 두 리스트 묶기
reversed(list)              # 역순 반복
sorted(list)                # 정렬된 새 리스트

# 논리/판별
all([True, True, False])    # False (모두 참?)
any([True, False, False])   # True (하나라도 참?)
isinstance(obj, type)       # 타입 확인

# 고차 함수
map(func, iterable)         # 각 요소에 함수 적용
filter(func, iterable)      # 조건 필터링
sorted(iterable, key=func)  # 정렬 기준 지정

유용한 패턴

# 조기 반환 (Early Return)
def get_grade(score):
    if score >= 90: return 'A'
    if score >= 80: return 'B'
    if score >= 70: return 'C'
    return 'F'

# 기본값 처리
def process(data=None):
    if data is None:
        data = []
    # ...

# 언패킹 활용
def get_user():
    return "Alice", 25, "Seoul"

name, age, city = get_user()

# 함수를 인자로 전달
def apply_twice(func, value):
    return func(func(value))

apply_twice(lambda x: x * 2, 3)  # 12