Skip to the content

When not to use it

Python · Unit 11: Recursion

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. 1. Predict the output

    What does this code print?

  2. 2. Multiple choice

    What does a RecursionError mean?

  3. 3. Find the bug

    This program should print 81, which is 3 to the power of 4. Which line has the bug?

  4. 4. Find the case that fails

    add_up_to(n) should return 1 + 2 + ... + n, or 0 if n is 0 or negative. Which call does it fail on?

  5. 5. Multiple choice

    You need to add up the year's 10,000 sales, stored in a list. What's the better choice?

  6. 6. Predict the output

    This is fact written with a loop. What does it print?

  7. 7. Complete the code

    This is countdown with a loop. Fill in the blank so it prints 3, 2, 1 and Liftoff!

  8. 8. Put the lines in order

    Put the loop version of flip in order.

  9. 9. Predict the output

    Here the function calls itself with each inner list. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →