Honestly, when I first heard about recursion I thought — why even bother, loops work fine.
And I was right. For simple stuff, loops ARE easier.
But then I hit problems where loops started getting messy and recursion just... made sense.
So what even is recursion?
A function that calls itself. That's it.
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
See that? factorial calling factorial. The function solves a smaller version of the same problem until it hits the base case and stops.
Loop vs Recursion — honest take
| Loop | Recursion | |
|---|---|---|
| Simple problems | ✅ easier | feels overkill |
| Nested/tree structures | gets messy | ✅ clean |
| Memory | efficient | uses call stack |
| Readability | straightforward | takes time to click |
When recursion actually wins
When the problem itself is repetitive in nature — like a folder inside a folder inside a folder. You don't know how deep it goes. A loop struggles. Recursion handles it naturally.
Same with backtracking — maze solving, sudoku. You try a path, it fails, you go back and try another. That "go back" part is just recursion doing its thing.
Top comments (0)