What is recursion?
- Algorithms course
- Beginner
- Lesson 37/80
- 4 min
A function calling itself is recursion.
What is recursion?
Recursion is when a function calls itself. It solves a problem by breaking it into smaller instances of the same problem.
Every recursive function has two parts: a base case (stopping condition) and a recursive step (self-call).
Base case
The base case is the condition where recursion stops. Without it, the function calls itself forever and a stack overflow occurs.
The base case directly solves the smallest problem. For example, in countdown(0) the base case might be 'stop if 0'.
Practice Countdown
Write countdown(n). Print n, if n > 0 call countdown(n-1). Call countdown(3) to print 3, 2, 1.
Starter code
def countdown(n):
# Count downSample solution
def countdown(n):
# Count down
print(n)
if n > 0:
countdown(n - 1)
countdown(3)Expected output
3 2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is recursion?
- A sorting algorithm
- A type of loop
- A data structure
- A function calling itself Correct answer
Explanation: Recursion is a function calling itself.
2 Base case
The condition that stops recursion: ____
The condition that stops recursion: base case
Explanation: base case is right.
3 What is recursion: match the terms
| Term | Meaning |
|---|---|
Recursion |
Self-call |
Base case |
Stops |
Recursive step |
Reduces |
Stack overflow |
Infinite call |