💡
Exercise 81

Recursion Basics 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

Recursion is when a function calls itself! It's like looking into two mirrors facing each other — images within images within images... 🪞

💡 Think of it like this: Russian nesting dolls (matryoshka). To find the smallest doll, you open the big one, find a smaller one inside, open that, find an even smaller one... until you reach the tiniest doll (that's your base case!).

Every recursive function needs:

  • 🛑 Base case: When to STOP (without this → infinite loop → crash!)
  • 🔄 Recursive case: The function calls itself with a SMALLER problem
  • 📉 Progress: Each call must get closer to the base case
# Countdown — simplest recursion example def countdown(n): if n <= 0: # Base case: stop at 0 print('Go! 🚀') return print(n) countdown(n - 1) # Recursive case: smaller problem countdown(3) # Output: 3, 2, 1, Go! 🚀
# Factorial: 5! = 5 × 4 × 3 × 2 × 1 = 120 def factorial(n): if n <= 1: # Base case return 1 return n * factorial(n - 1) # n! = n × (n-1)! # How it works: # factorial(4) # = 4 * factorial(3) # = 4 * (3 * factorial(2)) # = 4 * (3 * (2 * factorial(1))) # = 4 * (3 * (2 * 1)) # = 4 * (3 * 2) # = 4 * 6 # = 24 ✓

Pro tip: When stuck with recursion, ask yourself: "If I had the answer to a smaller version of this problem, how would I use it to solve the bigger problem?"

📋 Instructions
Write a recursive function `sum_to_n(n)` that returns the sum of all numbers from 1 to n. Test with n=5 (15) and n=10 (55).
Base case: if n <= 0, return 0. Recursive case: return n + sum_to_n(n-1). sum_to_n(5) = 5 + sum_to_n(4) = 5 + 4 + sum_to_n(3) ... = 15.
🧪 Test Cases
Input
sum_to_n(5)
Expected
15
Test case 1
Input
sum_to_n(10)
Expected
55
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.