Recursion
Recursion
Sometimes a function can solve a problem by calling itself.
This is called recursion.
It may sound strange at first, but it becomes clear with simple examples.
What Is Recursion?
Recursion happens when a function runs itself.
The function keeps calling itself until a stopping point is reached.
Why a Stopping Point Matters
Without a stopping point, the function would call itself forever.
That would cause an error.
The stopping point is often called the base case.
Simple Example
def countdown(number):
if number == 0:
print("Done")
else:
print(number)
countdown(number - 1)
countdown(3)
Output
3
2
1
Done
How This Works
Let’s go step by step:
countdown(3)prints3- Then it calls
countdown(2) - That prints
2 - Then it calls
countdown(1) - That prints
1 - Then it calls
countdown(0) - Now the base case is reached
- It prints
Done - The recursion stops
Another Example: Factorial
Factorial means multiplying numbers down to 1.
Example:
4! = 4 × 3 × 2 × 1 = 24
def factorial(number):
if number == 1:
return 1
else:
return number * factorial(number - 1)
print(factorial(4))
Output
24
Why Recursion Is Useful
Recursion is useful for problems that repeat in smaller steps.
Examples:
- Countdowns
- Factorials
- Folder search
- Tree structures
Common Beginner Mistake
Forgetting the base case.
def test():
test()
This never stops and causes an error.
Code Along
def show(number):
if number == 0:
print("End")
else:
print(number)
show(number - 1)
show(2)
Output
2
1
End
Mini Challenge
Build a countdown function.
Steps:
- Create a function called
countdown - Give it one parameter called
number - If number is
0, print:
Go! - Otherwise:
- Print the number
- Call the function again with
number - 1
Expected output for countdown(3):
3
2
1
Go!
Real World Use Case
Programs use recursion in file systems, search tools, games, and problems that break into smaller versions of themselves.
Quiz
- What is recursion?
- What is a base case?
- Why is the base case important?
- What happens if recursion never stops?
Assignment
Create a recursive function that prints numbers from 5 down to 1, then prints Finished.
Summary
You learned that recursion happens when a function calls itself and uses a base case to stop safely.