When not to use it
Python · Unit 11: Recursion
- Full plan
- Python
- 9 exercises
If a function never reaches its base case, it calls itself forever. Python doesn't wait forever: at around a thousand open calls it stops with RecursionError.
def drop(n):
return drop(n - 1)
try:
drop(5)
except RecursionError:
print("Too many calls")Prints
Too many calls
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. Multiple choice
What does a
RecursionErrormean?3. Find the bug
This program should print 81, which is 3 to the power of 4. Which line has the bug?
4. Find the case that fails
add_up_to(n)should return 1 + 2 + ... + n, or 0 ifnis 0 or negative. Which call does it fail on?5. Multiple choice
You need to add up the year's 10,000 sales, stored in a list. What's the better choice?
6. Predict the output
This is
factwritten with a loop. What does it print?7. Complete the code
This is
countdownwith a loop. Fill in the blank so it prints 3, 2, 1 and Liftoff!8. Put the lines in order
Put the loop version of
flipin order.9. Predict the output
Here the function calls itself with each inner list. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.