def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(4))
The function calls itself with decreasing values until it reaches 0, then multiplies back up.
4! = 4 * 3 * 2 * 1 = 24.
Tree traversal naturally fits recursion because each node can have multiple child nodes, which loops cannot easily handle without extra data structures.
def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) print(fib(-1))
The function never reaches a base case for negative input, so it keeps calling itself indefinitely until Python stops it.
def folder_size(folder): total = 0 for item in folder: if isinstance(item, int): total += item else: total += folder_size(item) return total nested_folder = [10, [5, 15], 20, [5, [10]]] print(folder_size(nested_folder))
The function sums integers directly and recursively sums nested lists.
10 + (5+15) + 20 + (5 + (10)) = 10 + 20 + 20 + 15 = 65.
Recursion allows a function to call itself with different inputs, naturally handling nested or branching data like trees.
Loops repeat code but do not call themselves, so they struggle with such structures without extra data management.
