Member-only story

Mastering Recursion in Python: The Good, Bad, & Ugly Truth

Dive into recursive functions with hands-on examples, learning the do’s, don’ts, and tradeoffs involved

Max N
3 min readMar 24, 2024

Recursion in programming refers to a method where a function calls itself repeatedly until a base case terminates execution. Although seemingly complex, recursion provides elegant solutions for various problems like factorials, Fibonacci sequences, tree traversals, and more.

Today, let’s dive deep into recursive functions in Python while addressing some misconceptions surrounding their performance and applicability.

The Basics

First things first: every recursive function requires two components — base cases and recursive cases. Base cases ensure termination; otherwise, infinite loops may occur. Meanwhile, recursive cases trigger additional iterations, gradually moving towards the base cases.

Let’s start with a classic example: computing the factorial of a number n (denoted as n!) via recursion. Mathematically, factorials follow this formula:

n! = {n × (n — 1) × … × 2} if n > 0
1 if n == 0

Our corresponding Python implementation looks like this:

def factorial(n)…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet