Lesson 24 of 34
Recursion: Functions that Call Themselves
10 min 35 XP
When a function calls itself, that's recursion. We turn a big problem into a smaller one of the same kind. A base case to stop is a must.
Example: edit me and press Run
Output Loading Python (first time takes a few seconds)
Press Run to see the result here.An interview favourite: n! (factorial). 5! = 5 × 4 × 3 × 2 × 1 = 120, which means 5! = 5 × 4!
Example: edit me and press Run
Output Loading Python (first time takes a few seconds)
Press Run to see the result here.Without a base case the function keeps calling itself forever, and Python stops it with a RecursionError.