Skip to content

Advanced Python · Week 7

Recursion

Step 1 of 5

Exercise 1: Introduction to Recursion

Welcome to Python 2, Lesson 7! Today, we'll learn about recursion, a powerful programming concept where a function calls itself to solve a problem.

What is Recursion?

Recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. In programming, recursion occurs when a function calls itself.

Let's start with a simple example of a recursive function that counts down from a given number:

def countdown(n): if n <= 0: print("Blastoff!") else: print(n) countdown(n - 1) countdown(5)

Now it's your turn! Create a recursive function called count_up that counts up from 1 to a given number:

  1. Define the function count_up(n)
  2. If n is greater than 5, print "Done!"
  3. Otherwise, print the current number and call count_up(n + 1)
  4. Test your function with count_up(1)
Starter code
# Define your count_up function here

# Test your function
count_up(1)

Write your code here