데이터 재료과학 (제 5강)

함수

1. 목표

2. 함수란

def add(a, b): #함수의 이름이 'add', 입력은 a와 b
   return a + b # 출력은 a+b
def sayhi(): # 함수의 이름이 'sayhi', 입력과 출력 없음
   print('Hi')
def func(a=3,b=5): # 함수의 이름이 'func', 입력 a와 b의 default가 있음.
  """
  a and b are the two arguments of this function
  and this function calculates a+b, then return the result as output
  """
  return a+b

아래 실행해보자

## default value 활용됨
print(func())

print(func(3,5))

print(func(5,3))

print(func(a=3,b=6))

print(func(b=6,a=3))

print(func.__doc__) ## docstring 출력
print(help(func))
print(help(help))
def f(a=3,b=5,c,d):
   print(a+b)
   print(c+d)
   return a*b*c*d

3. 모듈(module)과 import

4. Built-in functions (no import / no declaration required)

5. 가변 인자 (*args)

def add_all(*args):
    # args는 입력된 모든 숫자가 담긴 튜플 형태. 예: (1, 2, 3)
    return sum(args)

# 인자의 개수를 자유롭게 넣을 수 있습니다.
print(add_all(1, 2))        # 결과: 3
print(add_all(1, 2, 3, 4))  # 결과: 10

6. 키워드 가변인자 (**kwargs)

def print_info(**kwargs):
    # kwargs는 dictionary 형태. 예: {'name': 'Alice', 'age': 30}
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# 키워드 형태로 인자를 자유롭게 넘깁니다.
print_info(name="Alice", age=30, role="Professor")
# 출력:
# name: Alice
# age: 30
# role: Professor

7. 예시

7.1. 주어진 모든 가변인자를 순서대로 곱하여 출력하는 함수 만들기

7.2. 주어진 모든 가변인자의 개수를 출력하고, 그 가변인자의 총합과 평균을 구하는 함수 만들기