함수의 기본

함수는 코드의 집함이다. 함수를 생성하는 기본 형태는 다음과 같다.

def 함수 이름( ):
문장

기본적인 함수

def print_3times():
    print('hello world')
    print('hello world')
    print('hello world')

print_3times()
hello world
hello world
hello world

함수에 매개변수 만들기

def 함수 이름(매개변수, 매개변수, …):

### 매개변수의 기본

def print_3times(value, n):
    for i in range(n):
        print(value)

print_3times('hello', 5)
hello
hello
hello
hello
hello
def print_string(n, *values):
    for i in range(n):
        for value in values:
            print(value)
        
print_string(3, 'hello!', 'python', 'programming!')
hello!
python
programming!
hello!
python
programming!
hello!
python
programming!
def print_ntimes(value, n = 2):
    for i in range(n):
        print(value)
print_ntimes("hello world")
hello world
hello world
def return_test():
    print("A")
    return          # return 을 만나면 이후는 실행하지 않고 종료
    print("B")
return_test()

A

범위 내부의 정수를 모두 더하는 함수 만들기

def sum_all(start, end):
    output = 0
    for i in range(start, end + 1):
        output += i
    return output

print(sum_all(0, 100))
print(sum_all(0, 1000))
print(sum_all(50, 100))
5050
500500
3825

기본 매개변수와 키워드 매개변수를 활용

def sum_all(start = 0, end = 100, step = 1):
    output = 0
    for i in range(start, end+1, step):
        output += i
    return output
print(sum_all())
print(sum_all(end = 1000))
print(sum_all(start = 50, end = 100, step = 2))
5050
500500
1950

반복문으로 factorial 구하기

def factorial(n):
    output = 1
    for i in range(1, n+1):
        output *= i
    return output
print(factorial(5))

120

재귀함수(recursion)

재귀란 ‘자기 자신을 호출하는 것’ 을 의미한다.

재귀함수로 factorial 구하기

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

factorial(8)
40320

재귀함수로 fibonacci 수열 구하기

def fibonacci(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    else:
        return fibonacci(n-1)+fibonacci(n-2)
fibonacci(40)
102334155

memo 를 통한 fibonacci 수열 구하기

dic = {
    1:1,
    2:1
}
def fibonacci(n):
    if n in dic:
        return dic[n]
    else:
        return fibonacci(n-1)+fibonacci(n-2)
fibonacci(40)
102334155