Recursion in Python
Recursion is when a function calls itself to solve a smaller version of the same problem, continuing until it reaches a base case simple enough to answer directly without another call. Every recursive function needs exactly that: a base case that stops the recursion, and a recursive case that makes progress toward it.
Identify the base case
The simplest version of the problem, answerable directly with no further recursion.
Identify the recursive case
How to reduce the problem toward the base case, usually by calling the function again with a smaller input.
Each call waits for the next
Building up a chain of paused calls, each waiting on the one it made.
The chain unwinds from the base case
Once the base case is hit, calls start returning back up, each completing its paused work.
A broken base case recurses forever
Without genuine progress toward the base case, Python eventually raises a RecursionError.
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) print(factorial(5))Each recursive call waits on the stack until a deeper call returns, so a recursive function that makes n nested calls uses O(n) space for that call stack — unlike an equivalent loop, which typically uses O(1) space. This is one reason very deep recursion can hit Python's recursion limit or use noticeably more memory than a loop.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.