- 最終更新
- 2026/08/17
3秒でわかる
関数が自分自身を呼び出して問題を小さく分けていく書き方。階層の深さが決まっていない木構造やフォルダの探索を短く表すために使います。
30秒図解
もう少し詳しく
どういうものか
再帰は、
なぜ必要か
繰り返しの
具体例
import os
def find_py_files(path):
found = []
for name in os.listdir(path):
full = os.path.join(path, name)
if os.path.isdir(full):
found += find_py_files(full) # 自分を呼ぶ
elif name.endswith(".py"):
found.append(full)
return found
# 階乗は基底条件が分かりやすい例
def fact(n):
if n <= 1: # 基底条件
return 1
return n * fact(n - 1)つまずきやすいところ
止まらないRecursionError が
もうfib(n-1) と fib(n-2) の
覚え方
合わせ鏡ではなく、


