What recursion is
Python · Unit 11: Recursion
- Full plan
- Python
- 9 exercises
A function can call itself. That's called recursion.
countdown(3) prints 3 and asks countdown(2) to carry on. And so on, until it reaches 0.
def countdown(n):
if n == 0:
print("Liftoff!")
else:
print(n)
countdown(n - 1)
countdown(3)Prints
3 2 1 Liftoff!
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What if the countdown starts at 0?
3. Multiple choice
In
countdown, what makes the function stop?4. Complete the code
Fill in the blank so it adds 4 + 3 + 2 + 1.
5. Predict the output
What does this code print?
6. Find the bug
This program should print 6, the factorial of 3. Which line has the bug?
7. Put the lines in order
Put the function in order so it prints the factorial of 5.
8. Multiple choice
What does
power(b, e)calculate?9. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.