Skip to content

재귀함수

재귀함수 란

함수 안에서 함수 자기자신을 호출하는 함수

탈출 코드가 없으면 error 발생

def hello():
    print('Hello world')
    hello()    # 재귀 코드

hello()
>>> Hello world
    Hello world
    Hello world
    Hello world
    ...
    Hello world
    Hello world
    Traceback (most recent call last):
      File "main.py", line 5, in <module>
        hello()
      File "main.py", line 3, in hello
        hello()
      File "main.py", line 3, in hello
        hello()
      File "main.py", line 3, in hello
        hello()
      [Previous line repeated 992 more times]
      File "main.py", line 2, in hello
        print('Hello, world!')
    RecursionError: maximum recursion depth exceeded while calling a Python object

팩토리얼 구현

def factorial(n):
    if n == 1:
        return 1    # 탈출 코드
    return n * factorial(n - 1)    # 재귀 코드

print(factorial(5))
>>> 120